在 Ubuntu(Linux)下,opendir 本身不直接支持“递归遍历子目录”,它只负责打开一个指定的目录,返回一个 DIR * 句柄,然后你用 readdir 去读取该目录下的条目(包括子目录名,但不会自动进入子目录)。
opendir(path)
✅ 打开一个目录
❌ 不会自动读取子目录内容
readdir(dir)
返回 .、..、普通文件、子目录等
❌ 不会递归进入子目录
需要自己写递归逻辑,例如:
#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);
}
nftw()(POSIX,专门遍历目录树)find 命令glob()(有限支持)std::filesystem::recursive_directory_iterator✅ opendir 能用
❌ 不支持子目录自动遍历
✅ 子目录需要你手动递归处理
如果你是想做特定功能(如过滤文件、统计大小、删除目录),可以告诉我,我可以直接给你完整示例。