简短回答:readdir 本身不能递归,它只能读取单个目录下的条目;递归需要你在代码里自己实现。
readdir 是什么在 CentOS(以及所有 Linux / POSIX 系统)中:
opendir():打开一个目录readdir():读取目录中的一个条目(文件或子目录)closedir():关闭目录readdir 不会进入子目录,它只返回当前目录下的内容。
你需要:
readdir 遍历目录stat 判断是否是目录#include <stdio.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.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 fullpath[1024];
snprintf(fullpath, sizeof(fullpath), "%s/%s", path, entry->d_name);
struct stat st;
stat(full_path, &st);
if (S_ISDIR(st.st_mode)) {
printf("DIR: %s\n", fullpath);
list_dir(fullpath); // 递归
} else {
printf("FILE: %s\n", fullpath);
}
}
closedir(dir);
}
ftw / nftw(系统提供)#include <ftw.h>
int cb(const char *path, const struct stat *st, int type) {
printf("%s\n", path);
return 0;
}
int main() {
nftw(".", cb, 20, FTW_DEPTH);
}
find /path -type f
| 方式 | 是否递归 | 说明 |
|---|---|---|
readdir |
❌ 否 | 只能读一层 |
readdir + 自己写递归 |
✅ 是 | 常见做法 |
nftw |
✅ 是 | 系统封装 |
find |
✅ 是 | 命令行 |
如果你是用 C / C++ / Python / Shell 写,我可以给你对应版本的递归示例。