在 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);
✅ 只能列出 当前目录下的内容
❌ 不会自动进入子目录
你需要 自己写递归逻辑:
#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);
}
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);
}
✅ 自动递归
✅ 适合备份、扫描、统计
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,我可以给你最合适的示例。