Checking for Linux Subfolders

I am trying to check if there are any subfolders in the folder without iterating through my children in Linux. The closest I have found so far is using ftwand stopping in the first subfolder - or using scandirand filtering the results. Both, however, are redundant for my purposes, I just want yes / no.

On Windows, this is done by calling SHGetFileInfoand then testing dwAttributes & SFGAO_HASSUBFOLDERin the returned structure. Is there such an option in Linux?

+3
source share
3 answers

The standard answer is to call stat in the directory, then check the st_nlink field ("number of hard links"). In the standard file system, each directory has 2 hard links ( .and a link from the parent directory to the current directory), so each hard link outside 2 indicates a subdirectory (in particular, a subdirectory link ..to the current directory).

However, I understand that file systems are not required to implement this (see, for example, this mailing list ), therefore, operation is not guaranteed.

Otherwise, you must do what you do:

  • Iterate over the contents of a directory using glob with a GLOB_ONLYDIRGNU-specific flag , or scandir , or readdir .
  • stat S_ISDIR(s.st_mode), , . , , struct dirent.d_type: DT_DIR, , DT_UNKNOWN, .
+4

, ( e.James), , script, ++. , "++" , , , , API POSIX :

// warning: untested code.
bool has_subdir(char const *dir) { 
    std::string dot("."), dotdot("..");
    bool found_subdir = false;    
    DIR *directory;

    if (NULL == (directory = opendir(dir)))
        return false;

    struct dirent *entry;
    while (!found_subdir && ((entry = readdir(directory)) != NULL)) {
        if (entry->d_name != dot && entry->d_name != dotdot) {
            struct stat status;
            stat(entry->d_name, &status);
            found_subdir = S_ISDIR(status.st_mode);
        }
    }
    closedir(directory);
    return found_subdir;
}
+2

getdirentries , ? , shoudl , . , linux:(

0

Source: https://habr.com/ru/post/1739879/


All Articles