linux

linux readdir能否递归读取子目录

小樊
82
2024-12-29 09:34:20
栏目: 智能运维

readdir 本身不支持递归读取子目录

#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>

void listFiles(const char *path) {
    DIR *dir;
    struct dirent *entry;

    dir = opendir(path);
    if (dir == NULL) {
        perror("Failed to open directory");
        return;
    }

    while ((entry = readdir(dir)) != NULL) {
        char fullPath[256];
        snprintf(fullPath, sizeof(fullPath), "%s/%s", path, entry->d_name);

        if (entry->d_type == DT_DIR) {
            listFiles(fullPath); // 递归读取子目录
        } else {
            printf("%s\n", fullPath);
        }
    }

    closedir(dir);
}

int main() {
    const char *path = "."; // 从当前目录开始
    listFiles(path);
    return 0;
}

这个程序首先打开指定路径的目录,然后使用 readdir 读取目录中的每个条目。如果条目是一个子目录,程序会递归地调用 listFiles 函数来读取子目录中的文件。最后,程序会关闭目录并退出。

0
看了该问题的人还看了