在 Debian(以及一般的 Linux/Unix 系统)里,opendir 本身不能递归读取目录,它只能打开一个目录,然后配合 readdir 读取该目录下的直接条目(文件和子目录)。
opendir(const char *name)readdir(DIR *)opendir你需要在代码中手动递归:
#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);
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);
}
opendir + readdir ≠ findfind /path -type f
nftw()(POSIX,推荐)fts_open()(BSD 风格)✅ opendir 只能读一层
❌ 不能自动递归
✅ 递归必须自己写或用 nftw / find
如果你想要 C 语言递归示例 或 用 nftw 的实现,我可以给你现成代码。