在 Debian(以及所有 Linux/Unix 系统)里,readdir() 本身不能递归子目录,它只能读取一个目录里的条目(文件和子目录名),不会自动进入子目录。
readdir() 是什么readdir() 是 POSIX / C 标准库函数struct dirent,包含:
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);
}
ls -R ✅ 递归find /path ✅ 递归readdir() ❌ 不递归readdir() 来自 glibcreaddir_r()(线程安全,已废弃)scandir() + 递归,或 nftw()(专门遍历目录树)如果你说的是 Python / Shell / 某个具体语言里的 readdir,可以告诉我,我给你对应示例。