温馨提示×

ubuntu readdir能否递归

小樊
41
2026-10-24 05:00:42
栏目: 智能运维

简短结论:readdir 本身不能递归,它只读取当前目录下的条目,不包含子目录内容。


详细说明

1. readdir 是什么

在 Ubuntu / Linux 中,readdir(及其变体 readdir_r)是 POSIX / glibc 提供的目录读取函数:

#include <dirent.h>

struct dirent *readdir(DIR *dirp);
  • 每次调用返回一个目录项(struct dirent)
  • 只针对一个已打开的目录
  • 不会自动进入子目录

2. 为什么不能递归

readdir 的设计目标是:

“读一个目录,一次一项”

如果你要递归,需要自己写递归逻辑:

void list_dir(const char *path) {
    DIR *dir = opendir(path);
    struct dirent *entry;

    while ((entry = readdir(dir)) != NULL) {
        if (entry->d_type == DT_DIR) {
            // 递归调用
        }
    }
    closedir(dir);
}

⚠️ 注意:

  • DT_DIR 只是提示(某些文件系统不可靠)
  • 更稳妥的是用 stat() 判断是否是目录

3. 如果你想要“递归读取”

✅ 自己用 readdir + 递归

最常见方式(如上)

✅ ftw / nftw(标准库)

#include <ftw.h>

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

nftw("/path", cb, 20, FTW_DEPTH);

✅ 命令行(非 API)

find /path

4. 总结

问题 答案
readdir 能递归吗 ❌ 不能
能实现递归吗 ✅ 通过代码逻辑
推荐方式 readdir + stat 或 nftw

如果你愿意,我可以给你一个完整可编译的 Ubuntu C 递归列目录示例。

0 踩