【问题标题】:C: How to list the count of the number of files and sub-directories in a directoryC:如何列出一个目录中文件和子目录的数量
【发布时间】: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_type field is not supported by all filesystems.
  • 此外,如果您有符号链接或管道或任何其他非常规文件或目录,这些可能不会被您的程序计算在内,但会在执行时列出,例如ls -a.

标签: c file directory


【解决方案1】:

您的程序看起来合法(拼写错误除外)。

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

$./program-name DIR

(例如,$./program-name . 表示当前目录)。

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

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

代替计数目录

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

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

【讨论】:

    猜你喜欢
    • 2012-09-02
    • 1970-01-01
    • 2011-02-23
    • 2017-05-01
    • 2012-11-14
    • 2020-01-29
    • 1970-01-01
    相关资源
    最近更新 更多