在 Ubuntu / Linux 下,opendir() 本身不能递归子目录。
opendir():只打开一个目录,返回一个 DIR *readdir():读取该目录下的直接条目(文件和子目录)是否递归,完全由你在代码里自己实现。
#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("目录: %s\n", full);
list_dir(full); // 递归
} else {
printf("文件: %s\n", full);
}
}
closedir(dir);
}
✅ 用 opendir + readdir + 递归调用
❌ opendir 本身做不到
nftw()(更专业,支持递归遍历)find 命令(Shell 层)glob()(有限递归)如果你说的是 某个具体语言或库(如 Python、Go、C++ filesystem),可以告诉我,我可以给对应示例。