简短回答:readdir 本身不能递归,它只能读取一个目录下的条目,不能自动进入子目录。
在 CentOS(以及所有 Linux / POSIX 系统)中:
readdir() 是 C 库函数(#include <dirent.h>)DIR *dir = opendir("/path");
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
closedir(dir);
上面代码 只会列出 /path 下的内容,不会进入子目录。
常见做法:
readdir + stat)void list_dir(const char *path) {
DIR *dir = opendir(path);
struct dirent *entry;
char fullpath[1024];
while ((entry = readdir(dir)) != NULL) {
if (strcmp(entry->d_name, ".") == 0 ||
strcmp(entry->d_name, "..") == 0)
continue;
snprintf(fullpath, sizeof(fullpath), "%s/%s", path, entry->d_name);
struct stat st;
stat(fullpath, &st);
if (S_ISDIR(st.st_mode)) {
list_dir(fullpath); // 递归
} else {
printf("%s\n", fullpath);
}
}
closedir(dir);
}
ftw() / nftw()(标准库,支持递归)#include <ftw.h>
int cb(const char *path, const struct stat *st, int flag) {
printf("%s\n", path);
return 0;
}
nftw("/path", cb, 20, FTW_PHYS);
find /path
| 方式 | 是否递归 |
|---|---|
readdir |
❌ 否 |
readdir + 自己写递归 |
✅ 是 |
nftw |
✅ 是 |
find |
✅ 是 |
如果你是想 写 C 程序 / Shell 脚本 / 内核层面,可以告诉我具体场景,我可以给更合适的方案。