I'm trying to check if a folder has any subfolders without iterating through its children, in Linux. The closest I've found so far is using ftw
and stopping at the first subfolder - or using scandir
and filtering through the results. Both, are, however, an overkill for my purposes, I simply want a yes/no.
On Windows, this is done by calling SHGetFileInfo
and then testing dwAttributes & SFGAO_HASSUBFOLDER
on the returned structure. Is there such an option on Linux?
The standard answer is to call stat on the directory, then check the st_nlink field ("number of hard links"). On a standard filesystem, each directory is guaranteed to have 2 hard links (.
and the link from the parent directory to the current directory), so each hard link beyond 2 indicates a subdirectory (specifically, the subdirectory's ..
link to the current directory).
However, it's my understanding that filesystems aren't required to implement this (see, e.g., this mailing list posting), so it's not guaranteed to work.
Otherwise, you have to do as you're doing:
GLOB_ONLYDIR
flag, or scandir, or readdir.S_ISDIR(s.st_mode)
to verify that files found are directories. Or, nonportably, check struct dirent.d_type
: if it's DT_DIR
then it's a file, and if it's DT_UNKNOWN
, you'll have to stat it after all.