在 Debian(Linux) 下,readdir 本身不能递归遍历目录,它只能读取当前目录中的一个条目(一次调用返回一个文件/子目录)。
readdir 是什么readdir 是 POSIX / glibc 提供的函数opendir / readdir / closedir 使用示例(只能列出当前目录):
DIR *dir = opendir(".");
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
closedir(dir);
需要 自己写递归逻辑:
#include <dirent.h>
#include <stdio.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);
printf("%s\n", full);
struct stat st;
if (stat(full, &st) == 0 && S_ISDIR(st.st_mode)) {
list_dir(full); // 递归
}
}
closedir(dir);
}
如果你不想自己写递归:
ftw / nftw(标准库)#include <ftw.h>
int cb(const char *path, const struct stat *st, int type, struct FTW *ftwbuf) {
printf("%s\n", path);
return 0;
}
int main() {
nftw(".", cb, 20, FTW_DEPTH);
}
find 命令(最简单)find /path -type f
| 方式 | 是否递归 | 说明 |
|---|---|---|
readdir |
❌ | 仅单层 |
readdir + 递归代码 |
✅ | 常见做法 |
nftw |
✅ | 推荐 |
find |
✅ | 命令行 |
如果你是在 C / C++ / Shell / Python 里用,我可以给你对应示例。