在 Debian(以及一般 Linux/Unix) 里,readdir 本身不能递归。
readdir 是什么readdir 是 POSIX 标准中的函数(在 <dirent.h> 中定义),作用是:
读取一个已打开目录流中的下一个目录项(entry)
原型:
struct dirent *readdir(DIR *dirp);
它只做一件事:遍历当前目录下的直接子项(文件或子目录),不会自动进入子目录。
readdir 只返回一个 dirent所以:
✅
readdir= 单层遍历
❌readdir≠ 递归遍历
需要你自己在代码里递归调用:
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
void list_dir(const char *path) {
DIR *dir = opendir(path);
struct dirent *entry;
char full[1024];
while ((entry = readdir(dir)) != NULL) {
if (strcmp(entry->d_name, ".") == 0 ||
strcmp(entry->d_name, "..") == 0)
continue;
snprintf(full, sizeof(full), "%s/%s", path, entry->d_name);
struct stat st;
stat(full, &st);
if (S_ISDIR(st.st_mode)) {
list_dir(full); // 递归
} else {
printf("%s\n", full);
}
}
closedir(dir);
}
如果你只是想在 Debian 上递归列出目录:
find /path
# 或
ls -R /path
nftw()(递归遍历文件系统)fts_open()(更现代)| 问题 | 答案 |
|---|---|
readdir 能递归吗 |
❌ 不能 |
| 需要自己递归吗 | ✅ 需要 |
| Debian 特有吗 | ❌ 不是,POSIX 标准 |
如果你是想用 C / Python / shell / 某个具体场景,我可以给你更针对性的例子。