简短结论:Linux 的 readdir() 本身不能递归,它只能读取一个目录下的条目(不进入子目录)。
readdir() 是什么readdir() 是 POSIX / glibc 提供的函数opendir() / closedir() 使用struct dirent *)示例:
DIR *dir = opendir("/path");
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
// 只列出 /path 下的直接内容
}
closedir(dir);
需要你自己写递归逻辑:
readdir() 读取目录stat() / lstat() 判断是否是目录opendir() + readdir()示例(简化):
void list_dir(const char *path) {
DIR *dir = opendir(path);
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);
struct stat st;
lstat(full, &st);
if (S_ISDIR(st.st_mode)) {
list_dir(full); // 递归
} else {
printf("%s\n", full);
}
}
closedir(dir);
}
find /pathnftw()(更推荐做递归遍历)std::filesystem::recursive_directory_iterator| 问题 | 答案 |
|---|---|
readdir() 能递归吗 |
❌ 不能 |
| 能靠它实现递归吗 | ✅ 可以(自己写) |
| 有现成递归函数吗 | ✅ nftw() |
如果你愿意,我可以给你一个完整可编译的递归目录遍历 C 程序。