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

在此代码中,我从目录中获取所有子目录路径。它工作正常,但我想添加更多内容,即计算所有子目录并打印它们。如何在此功能中执行此操作。我使用该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.

代码

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/%sn", path, name);
        printf("%s", path1);
        printf("%zun", count);
        count++;
    }
    closedir (dir); 
}

回答

您的代码存在一些问题:

正如托马斯上面所说:

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

  1. 您没有初始化count为零。
  2. 您在循环内打印。
  3. 您计算除.and之外的所有内容..,而不检查它是文件还是目录

这是(希望)您的代码的固定版本

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/%sn", path, name);
            printf("%s", path1);
        }
    }
    printf("nCounted: %u subdirectories.n", count);
    closedir (dir); 
}

编辑:根据chux-ReinstateMonica的评论编辑了我的代码

次要:当无符号计数肯定没问题时, size_t 计数的原因不大。size_t 取决于内存 - 而不是文件空间。迂腐地可以使用 uintmax_t。IAC,“%d”不是与 size_t 一起使用的指定匹配说明符 - 从 OP 的匹配“%zu”倒退了一步

  • @chux-ReinstateMonica Thank you, was used to using `size_t` for any unsigned data.
    (Assuming he isn't working on a filesystem from some martian futuristic civilization where file you store billions of files in the same directory, I doubt `uintmax_t` is absolutely necessary)

以上是如何计算目录中存在的所有子目录?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>