在 Ubuntu / Linux 下,opendir() 本身不能递归遍历目录,它只能打开单个目录并配合 readdir() 读取该目录下的条目(文件和子目录)。
opendir():打开一个目录readdir():读取目录项closedir():关闭目录它们只处理一层目录,不会自动进入子目录。
你需要 自己写递归逻辑(或在循环里处理子目录)。
#include <stdio.h>
#include <dirent.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("目录: %s\n", full);
list_dir(full); // 递归
} else {
printf("文件: %s\n", full);
}
}
closedir(dir);
}
int main() {
list_dir(".");
return 0;
}
std::filesystem::recursive_directory_iterator(C++17)find /path -type fos.walk() / pathlib如果你是用 C / C++ / 某种特定语言,可以告诉我,我可以给对应示例。