在 Debian(以及一般的 Linux/glibc) 中,opendir() 本身不能递归遍历目录,它只能打开并读取单个目录的内容。
opendir / readdir 的能力opendir():打开一个目录readdir():读取该目录下的直接子项(文件或子目录)示例(非递归):
DIR *dir = opendir("/path");
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 traverse(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)) {
traverse(full); // 递归
} else {
printf("%s\n", full);
}
}
closedir(dir);
}
如果不坚持用 opendir,可以用:
ftw() / nftw()(标准库,支持递归)find 命令glob()(有限递归)✅ opendir 可以用于递归遍历的基础
❌ 但 不能自动递归,必须自己实现递归逻辑
如果你需要 C 示例 / nftw 示例 / 性能注意点,可以继续问我。