c - 无法递归访问子文件夹

标签 c linux recursion directory filesystems

<分区>

我正在尝试构建一个程序,以递归方式列出目录中的所有文件夹和文件及其文件大小。我仍在处理第一部分,因为该程序似乎只深入了一个子文件夹级别。

有人能在这里发现问题吗?我卡住了。

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <strings.h>
#include <dirent.h>
#include <unistd.h>

void listdir(const char *name) {
    DIR *dir;
    struct dirent *entry;
    int file_size;

    if (!(dir = opendir(name)))
        return;
    if (!(entry = readdir(dir)))
        return;

    do {
        if (entry->d_type == DT_DIR) {
            char path[1024];
            if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
                continue;
            printf("./%s\n", entry->d_name);
            listdir(entry->d_name);
        }
        else
            printf("./%s\n", entry->d_name);
    } while (readdir(dir) != NULL);
    closedir(dir);
}

int main(void)
{
    listdir(".");
    return 0;
}

最佳答案

第一个问题是在while条件下,你放弃了readdir的返回值,它应该赋值给entry。

此外,当递归调用 listdir 时,您应该在路径前加上父名称,否则它将始终从当前工作目录搜索。 试试这个版本:

void listdir(const char *name) {
    DIR *dir;
    struct dirent *entry;
    int file_size;

    if (!(dir = opendir(name)))
            return;

    while ((entry = readdir(dir)) != NULL) {   // <--- setting entry
            printf("%s/%s\n", name, entry->d_name);
            if (entry->d_type == DT_DIR) {
                    char path[1024];
                    if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
                            continue;
                    sprintf(path, "%s/%s", name, entry->d_name);  // <--- update dir name properly by prepend the parent folder.
                    listdir(path);
            }
    }
    closedir(dir);
}

int main(void)
{
    listdir(".");
    return 0;
}

关于c - 无法递归访问子文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43038217/

相关文章:

c - 如何在C程序中使用环境变量

c - 在非常长的字符串中查找频率的最佳方法

c - SocketCan Can ID 优先级

java - 在java中使用递归反转整数列表数组

java - 使用jsp将递归结构转换为xml

c++ - 在 C/C++ 中实现 UNUSED 宏的通用编译器独立方式

c - 在 C 中打印字符串的一部分

Linux 查找给定多个字符或字符串的文件

linux - 如何并行执行 4 个 shell 脚本,我不能使用 GNU 并行?

recursion - Angular2递归组件