温馨提示×

ubuntu readdir能否递归读取

小樊
43
2026-10-15 09:29:54
栏目: 智能运维

在 Ubuntu(Linux) 上,readdir 本身不能递归读取目录,它只能:

读取一个打开目录流中的“当前层”条目(文件和子目录名)


一、readdir 是什么

readdir 是 POSIX 标准函数(在 <dirent.h> 中),用于:

#include <dirent.h>

DIR *dir = opendir("/path");
struct dirent *entry;

while ((entry = readdir(dir)) != NULL) {
    printf("%s\n", entry->d_name);
}
closedir(dir);

✅ 只能列出 当前目录下的内容
❌ 不会自动进入子目录


二、如何实现“递归读取”

你需要 自己写递归逻辑:

示例(C 语言递归遍历目录)

#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>

void list_dir(const char *path) {
    DIR *dir = opendir(path);
    if (!dir) return;

    struct dirent *entry;
    while ((entry = readdir(dir)) != NULL) {
        if (strcmp(entry->d_name, ".") == 0 ||
            strcmp(entry->d_name, "..") == 0)
            continue;

        char full[1024];
        snprintf(full, sizeof(full), "%s/%s", path, entry->d_name);
        printf("%s\n", full);

        struct stat st;
        if (stat(full, &st) == 0 && S_ISDIR(st.st_mode)) {
            list_dir(full);  // 递归
        }
    }
    closedir(dir);
}

三、更现代 / 更简单的方式(推荐)

1️⃣ nftw()(标准库,递归遍历)

#include <ftw.h>

int cb(const char *path, const struct stat *st, int type, struct FTW *ftw) {
    printf("%s\n", path);
    return 0;
}

int main() {
    nftw("/path", cb, 20, FTW_PHYS);
}

✅ 自动递归
✅ 适合备份、扫描、统计


2️⃣ C++17 std::filesystem

#include <filesystem>
namespace fs = std::filesystem;

for (auto &p : fs::recursive_directory_iterator("/path")) {
    std::cout << p.path() << "\n";
}

✅ 最简洁
✅ Ubuntu 20.04+ 默认支持


四、总结

方法 是否递归 说明
readdir ❌ 只能读一层
readdir + 自己递归 ✅ 传统方式
nftw ✅ 标准库递归
std::filesystem ✅ 最推荐

如果你告诉我你用的是 C / C++ / shell / Python,我可以给你最合适的示例。

0 踩