C:如何列出目录中文件和子目录的数量

C:如何列出目录中文件和子目录的数量,c,file,directory,C,File,Directory,有人能告诉我,我是否正确地找到了目录中的文件和子目录的数量?另外,我如何在终端上确认这一点 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

有人能告诉我,我是否正确地找到了目录中的文件和子目录的数量?另外,我如何在终端上确认这一点

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);
}
main(整数n,字符*路径[]){
//计算文件和子目录的数量
int fileCount=0;
int dirCount=0;
DIR*dp;
结构方向*dir;
int i;
对于(i=1;id_type==DT_REG){
fileCount++;
}
if(dir->d_type==DT_dir)
dirCount++;
}
printf(“%s:文件计数为:%d,目录计数为:%d\n”),路径[i],文件计数,目录$
}
//printf(“文件计数为:%d,目录计数为:%d”,文件计数,目录计数);
closedir(dp);
}
您的程序看起来合法(打字错误除外)

要在编译后在终端上测试它,只需键入

$/程序名目录

(例如,
$/程序名。
用于当前目录)

它将统计文件和目录,包括隐藏文件和.and..特殊目录。它不会在子目录中重复出现。*NIX命令在不递归的情况下统计目录中的文件(包括隐藏文件):

$find DIR-type f-maxdepth 1 | wc-l

而是用来计算目录

$find DIR-type d-maxdepth 1 | wc-l


(注意:您必须在目录计数中添加1,因为..目录将不被计数)

您可以通过实际转到其中一个目录并在那里列出所有文件来验证它。请记住,在您的程序对隐藏的文件和目录进行计数时,也要列出它们(包括
目录)@JoachimPileborg但是否有一个命令可以列出文件或目录子目录的计数?我认为我的代码是错误的,因为当我实际显示文件时,我的计数似乎很短……如果您使用的是Linux或OSX系统,请使用
ls-Fa
列出,这将显示隐藏的文件及其类别(常规文件、目录、管道等)。您也可以这样做,例如
find/path/to/dir-maxdepth 1-type d-o-type f | wc-l
来计算
/path/to/dir
中的所有常规文件和目录。您不使用它的原因是什么?
opendir()
/
readdir()
/
/
closedir()
nftw()
都是POSIX.1-2001函数,但是
nftw()
应该处理问题情况(如相关目录树中的重命名和删除)正确,而你的“重新发明轮子”方法肯定不会。此外,。此外,如果你有符号链接或管道或任何其他非常规文件或目录,这些文件或目录可能不会被你的程序计算在内,但会在执行时列出,例如
ls-a