Search code examples
cfilecountingstat

How to count only the number of directories from a path


I am trying to count only the directories from a path, but it doesn't work. So, i don't want to number both files and directories, i want only the directories. Could you help me, please? The code:

int listdir(char *dir) {
    struct dirent *dp;
    struct stat s;
    DIR *fd;
    int count = 0;

    if ((fd = opendir(dir)) == NULL) {
        fprintf(stderr, "listdir: can't open %s\n", dir);
    }
    while ((dp = readdir(fd)) != NULL) {
        if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
            continue;
        stat(dp->d_name, &s);
        if (S_ISDIR(s.st_mode))
        count++;
    }
    closedir(fd);
    return count;
}

Solution

  • your stat() call will fail, since you are not in the correct directory. This you can solve by either changing the current directory, or generate full paths and give to stat as argument.

    Some Unixes, you can optimize away the stat call by looking at struct dirent, the d_type field

    int listdir(char *dir) {
        struct dirent *dp;
        struct stat s;
        DIR *fd;
        int count = 0;
    
        if ((fd = opendir(dir)) == NULL) {
            fprintf(stderr, "listdir: can't open %s\n", dir);
        }
        chdir (dir); /* needed for stat to work */
        while ((dp = readdir(fd)) != NULL) {
            if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
                continue;
    #ifdef _DIRENT_HAVE_D_TYPE
            switch (dp->d_type)
            {
              case DT_UNKNOWN:
                stat(dp->d_name, &s);
                if (S_ISDIR(s.st_mode)) count++;
                break;
              case DT_DIR:
                count++;
                break;
            }
    #else
            stat(dp->d_name, &s);
            if (S_ISDIR(s.st_mode)) count++;
    #endif            
        }
        closedir(fd);
        return count;
    }