在 Debian(以及所有 Linux/Unix 系统)里,readdir 本身不能递归子目录。
readdir 是什么readdir 是 POSIX 标准 C 库函数(在 <dirent.h> 中),作用是:
读取一个已经打开的目录流中的“下一个目录项”
它只能:
DIR *dir = opendir("/path");
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
// 只能拿到当前目录下的名字
}
需要你自己写递归逻辑:
#include <dirent.h>
#include <sys/stat.h>
#include <string.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);
}
nftw()(推荐)#include <ftw.h>
int cb(const char *path, const struct stat *st, int type, struct FTW *ftw) {
printf("%s\n", path);
return 0;
}
int main() {
nftw("/path", cb, 20, FTW_DEPTH);
}
find /path
| 方式 | 是否递归 |
|---|---|
readdir |
❌ 不递归 |
readdir + 递归代码 |
✅ |
nftw |
✅ |
find |
✅ |
如果你是在 写 C 程序 / Python / Shell 或关心 性能/安全性(符号链接),可以告诉我,我可以给更合适的方案。