在 Ubuntu(Linux)下,opendir 本身不能递归子目录。
opendir() 只是打开一个目录流,返回一个 DIR *,用于读取当前目录下的条目(文件和子目录名)。readdir() 读取目录项d_type == DT_DIRopendir()#include <stdio.h>
#include <dirent.h>
#include <string.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);
printf("%s\n", full);
if (entry->d_type == DT_DIR)
list_dir(full);
}
closedir(dir);
}
int main() {
list_dir(".");
return 0;
}
opendir 属于 POSIX 标准,Linux / Ubuntu 都支持nftw()(标准库)ftw()(较旧)find✅ opendir 只能打开单层目录
❌ 不能递归
✅ 递归必须自己写逻辑或用其他接口
如果你是想在 shell / Python / C++ 里递归目录,也可以告诉我。