2015-05-07 26 views
0

有人可以告诉我,如果我正确地执行此操作以查找目录中的文件和子目录的数量吗?另外,如何在终端上确认这一点?C:如何列出目录中的文件和子目录的数量的计数

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); 
} 
+0

您可以通过实际转到其中一个目录并在其中列出所有文件来验证它。请记住列出隐藏的文件和目录,因为您的程序也会计算它们(包括'.'和'..'目录)。 –

+0

@JoachimPileborg,但有没有一个命令将列出目录的文件或子目录的计数?我认为我的代码是错误的,因为当我实际显示文件时,我的计数似乎很短... –

+1

如果你在一个Linux或OSX系统,使用'ls -Fa'列表,它将显示隐藏文件及其类别(常规文件,目录,管道等)。你也可以做例如'find/path/to/dir -maxdepth 1 -type d -o -type f | wc -l'来计算'/ path/to/dir'中的所有常规文件和目录。 –

回答

0

你的程序看起来是合法的(除了错别字)。

要测试编译之后在终端上简单地键入

$./program-name DIR

(例如$./program-name .为当前目录)。

它会统计文件和目录,包括隐藏文件和。和..特殊目录。它不会在子目录内重复出现。 * NIX命令没有递归计算一个目录下(包括隐藏文件)文件:

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

相反计数目录

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

(注:你要1添加到目录因为..目录不会计数)

相关问题