在 CentOS(以及其他 Linux 系统) 上,readdir 本身不能递归子目录。
readdir 是什么readdir 是 POSIX / glibc 提供的函数(在 <dirent.h> 中),用于:
opendir)struct direntDIR *dir = opendir(path);
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
// 只能看到当前目录下的文件/子目录
}
它 只遍历一层目录,不会自动进入子目录。
需要 自己写递归逻辑:
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);
if (entry->d_type == DT_DIR) {
list_dir(full); // 递归
}
}
closedir(dir);
}
如果你只是 命令行使用,而不是写 C 程序:
find /path -type fls -Rtree如果是 C/C++ 程序,还可以用:
nftw()(推荐,标准且安全)fts_open()(更现代)✅ readdir 不能递归
✅ 必须通过 代码递归调用 或 系统提供的高级接口 实现
✅ CentOS 与内核、glibc 版本无关,行为一致
如果你是在 写 C / C++ 程序、shell 脚本、或者 Python,可以告诉我具体场景,我可以给更合适的方案。