简短结论:readdir 本身不能递归子目录,它只能读取一个目录下的条目(文件/子目录名),是否递归要由你在代码里自己实现。
readdir 是什么readdir 是 POSIX 标准函数(<dirent.h>):
struct dirent *readdir(DIR *dirp);
作用:
opendir)它只知道:
d_named_type)readdir 不会:
它只做一件事:读当前目录的下一个条目
典型做法:
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
#include <stdio.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);
struct stat st;
stat(full, &st);
if (S_ISDIR(st.st_mode)) {
printf("DIR: %s\n", full);
list_dir(full); // 递归
} else {
printf("FILE: %s\n", full);
}
}
closedir(dir);
}
ftw / nftw#include <ftw.h>
int cb(const char *path, const struct stat *st, int type) {
printf("%s\n", path);
return 0;
}
nftw(".", cb, 20, FTW_DEPTH);
find 命令find . -type f
| 方式 | 是否递归 |
|---|---|
readdir |
❌ 不递归 |
readdir + 自己写 |
✅ 可递归 |
nftw |
✅ 直接递归 |
find |
✅ 最简单 |
如果你愿意,我可以:
d_type 性能陷阱readdir vs getdents