在 Debian(以及一般 Linux/POSIX 系统)里,opendir() 本身不能递归读取目录。
opendir() / readdir() 只能打开并遍历一个目录下的直接条目一般做法是用 opendir + readdir + stat,遇到目录就递归:
#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);
}
find /pathnftw()(标准库,支持递归)std::filesystem::recursive_directory_iterator(C++17)
opendir只能读一层目录,递归必须自己实现或用其他接口。
如果你需要 C / C++ / Shell / Python 的具体递归示例,我可以按你用的语言给。