【发布时间】:2015-05-07 07:36:46
【问题描述】:
谁能告诉我是否正确地执行了此操作以查找目录中的文件数和子目录?另外,如何在终端中确认这一点?
main(int n, char *path[]){
//count the number of files and subdirectories
int fileCount = 0;
int dirCount = 0;
DIR *dp;
struct dirent *dir;
int i;
for(i = 1; i < n; i++){
dp = opendir(path[i]);
if(dp==NULL)
continue;
while((dir = readdir(dp)) != NULL){
if(dir->d_type == DT_REG){
fileCount++;
}
if(dir->d_type == DT_DIR)
dirCount++;
}
printf("%s: file count is: %d and dir count is: %d\n",path[i], fileCount, dirCoun$
}
// printf("file count is: %d and dir count is: %d", fileCount, dirCount);
closedir(dp);
}
【问题讨论】:
-
您可以通过实际转到其中一个目录并在其中列出所有文件来验证它。记得列出隐藏的文件和目录,因为你的程序也会计算它们(包括
.和..目录)。 -
@JoachimPileborg 但是是否有一个命令可以列出目录的文件或子目录的数量?我认为我的代码是错误的,因为当我实际显示文件时,我的计数似乎很短......
-
如果你在例如Linux 或 OSX 系统,使用
ls -Fa列出,将显示隐藏文件及其类别(常规文件、目录、管道等)。你也可以做例如find /path/to/dir -maxdepth 1 -type d -o -type f | wc -l统计/path/to/dir中的所有常规文件和目录。 -
您没有为此使用
nftw()有什么原因吗?opendir()/readdir()/closedir()和nftw()都是 POSIX.1-2001 函数,但nftw()应该正确处理问题情况(如相关目录树中的重命名和删除),而你的 reinvent -the-wheel 方法绝对不会。此外,d_typefield is not supported by all filesystems. -
此外,如果您有符号链接或管道或任何其他非常规文件或目录,这些可能不会被您的程序计算在内,但会在执行时列出,例如
ls -a.