简单回答:readdir 本身不能递归子目录,它只能读取当前目录下的条目(文件或子目录名)。
readdir 是什么readdir 是 POSIX 标准中的函数(在 <dirent.h> 中),配合下面这些函数使用:
opendir()
readdir()
closedir()
它每次只返回一个目录项(struct dirent *),例如:
d_type == DT_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);
if (entry->d_type == DT_DIR) {
printf("DIR: %s\n", full);
list_dir(full); // 递归
} else {
printf("FILE: %s\n", full);
}
}
closedir(dir);
}
d_type 在某些情况下可能不可靠(如某些文件系统),可用 stat() 判断如果你只是想递归遍历目录,而不一定要用 readdir:
find, ls -Rstd::filesystem::recursive_directory_iterator✅ readdir 只能读一层目录
❌ 不能自动递归
✅ 递归需要你自己写逻辑
如果你愿意,我可以给你一个安全版递归函数或非递归版本。