使用C计算目录中的文件数

pen*_*uru 17 c linux file

如何在Linux平台上使用C计算目录中的文件数.

Mic*_*ngh 38

不保证此代码编译,并且它实际上只与Linux和BSD兼容:

#include <dirent.h>

...

int file_count = 0;
DIR * dirp;
struct dirent * entry;

dirp = opendir("path"); /* There should be error handling after this */
while ((entry = readdir(dirp)) != NULL) {
    if (entry->d_type == DT_REG) { /* If the entry is a regular file */
         file_count++;
    }
}
closedir(dirp);
Run Code Online (Sandbox Code Playgroud)

  • 如果要处理子目录中的文件,可以在遇到目录条目时进行递归.确保排除"." 和".."如果你这样做. (3认同)
  • 如果有人想知道为什么必须循环遍历以及为什么没有函数可以在恒定时间内获取目录中有多少文件,我发现了这个:http://blogs.msdn.com/b/oldnewthing/archive/2009 /02/17/9426787.aspx (3认同)
  • POSIX 仅指定 d_ino 和 d_name 作为 dirent-structure 的成员。此代码测试特定于平台的 d_type。 (2认同)