简短结论:readdir 本身不能递归,它只读取当前目录下的条目,不包含子目录内容。
readdir 是什么在 Ubuntu / Linux 中,readdir(及其变体 readdir_r)是 POSIX / glibc 提供的目录读取函数:
#include <dirent.h>
struct dirent *readdir(DIR *dirp);
struct dirent)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() 判断是否是目录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);
find /path
| 问题 | 答案 |
|---|---|
readdir 能递归吗 |
❌ 不能 |
| 能实现递归吗 | ✅ 通过代码逻辑 |
| 推荐方式 | readdir + stat 或 nftw |
如果你愿意,我可以给你一个完整可编译的 Ubuntu C 递归列目录示例。