C 如何计算目录中存在的所有子目录?

C 如何计算目录中存在的所有子目录?,c,C,在这段代码中,我从一个目录中获取所有子目录路径。它工作得很好,但是我想添加更多的东西,那就是计算所有的子目录并打印它们。如何在此函数中执行此操作。我使用了count变量使其工作,但结果如下 给定结果: /home/runner/TestC1/file 15775232 /home/runner/TestC1/dsf 15775233 /home/runner/TestC1/main.c 15775234 /home/runner/TestC1/main 15775235 /home/runne

在这段代码中,我从一个目录中获取所有子目录路径。它工作得很好,但是我想添加更多的东西,那就是计算所有的子目录并打印它们。如何在此函数中执行此操作。我使用了
count
变量使其工作,但结果如下

给定结果:

/home/runner/TestC1/file
15775232
/home/runner/TestC1/dsf
15775233
/home/runner/TestC1/main.c
15775234
/home/runner/TestC1/main
15775235
/home/runner/TestC1/file
/home/runner/TestC1/dsf
/home/runner/TestC1/main.c
/home/runner/TestC1/main

Counted: 4 subdirectories.
预期结果:

/home/runner/TestC1/file
15775232
/home/runner/TestC1/dsf
15775233
/home/runner/TestC1/main.c
15775234
/home/runner/TestC1/main
15775235
/home/runner/TestC1/file
/home/runner/TestC1/dsf
/home/runner/TestC1/main.c
/home/runner/TestC1/main

Counted: 4 subdirectories.
代码

void listdir(void){
    DIR *dir;
    struct dirent *entry;
    size_t count;

    if (!(dir = opendir(path))) {  
        perror ("opendir-path not found");
        return;
    }

    while ((entry = readdir(dir)) != NULL) {  
        char *name = entry->d_name;
        if (entry->d_type == DT_DIR)  
            if (!strcmp(name, ".") || !strcmp(name, ".."))
                continue;
        snprintf (path1, 100, "%s/%s\n", path, name);
        printf("%s", path1);
        printf("%zu\n", count);
        count++;
    }
    closedir (dir); 
}

您的代码存在一些问题:

正如上面所说:

你没有初始化计数。你在循环中打印

  • 您没有将计数初始化为零
  • 你在循环中打印
  • 除了
    之外,您计算所有内容,而不检查它是文件还是目录
  • 这里有(希望)您的代码的固定版本

    void listdir(void){
        DIR *dir;
        struct dirent *entry;
        unsigned count = 0;
    
        if (!(dir = opendir(path))) {  
            perror ("opendir-path not found");
            return;
        }
    
        while ((entry = readdir(dir)) != NULL) {  
            char *name = entry->d_name;
            if (entry->d_type == DT_DIR) {
                if (!strcmp(name, ".") || !strcmp(name, ".."))
                    continue;
                count++;
                snprintf (path1, 100, "%s/%s\n", path, name);
                printf("%s", path1);
            }
        }
        printf("\nCounted: %u subdirectories.\n", count);
        closedir (dir); 
    }
    
    编辑: 按编辑我的代码

    小调:当无符号计数当然可以时,没有什么理由进行大小计数。大小取决于内存,而不是文件空间。学究们可以使用uintmax\t。IAC“%d”不是与大小匹配的指定匹配说明符\u t-从OP的匹配“%zu”向后退一步


    您没有初始化
    计数
    。你在循环中打印。你应该只根据问题的标题来计算目录。您可以对每个文件以及子目录进行编码计数。将else块放在内部if之后,并在那里递增计数。初始化
    计数
    ,如前所述。依我看,如果也在外面的
    后面,你也需要大括号。当前嵌套的if可以(甚至可能应该)写为
    if(A&&(B||C))
    ,但是您需要更改它,以便您确实需要两个级别的操作。
    “opendir path not found”
    将导致非常混乱的错误消息,如
    opendir path not found:permission denied
    。只需编写
    perror(路径)
    @chux,谢谢,已经习惯于对任何未签名的数据使用
    size\t
    。(假设他不是在火星未来文明的某个文件系统上工作,在这个文件系统中,你在同一个目录中存储了数十亿个文件,我怀疑
    uintmax\u t
    绝对必要)评估
    count
    的类型可能是一个有趣的阅读。