Counting the number of files in a directory using C

前端 未结 4 793
执念已碎
执念已碎 2020-12-03 04:58

How can I count the number of files in a directory using C on linux platform.

4条回答
  •  难免孤独
    2020-12-03 05:58

    If you want to include subdirectories as well, you can use this function that I'm using in some of my code. You should probably modify it to include some more error checking and support different directory separators.

    int countfiles(char *path) {
        DIR *dir_ptr = NULL;
        struct dirent *direntp;
        char *npath;
        if (!path) return 0;
        if( (dir_ptr = opendir(path)) == NULL ) return 0;
    
        int count=0;
        while( (direntp = readdir(dir_ptr)))
        {
            if (strcmp(direntp->d_name,".")==0 ||
                strcmp(direntp->d_name,"..")==0) continue;
            switch (direntp->d_type) {
                case DT_REG:
                    ++count;
                    break;
                case DT_DIR:            
                    npath=malloc(strlen(path)+strlen(direntp->d_name)+2);
                    sprintf(npath,"%s/%s",path, direntp->d_name);
                    count += countfiles(npath);
                    free(npath);
                    break;
            }
        }
        closedir(dir_ptr);
        return count;
    }
    

提交回复
热议问题