在 Ubuntu / Linux 下,opendir() 本身不能递归遍历目录。
opendir() 只能:
readdir() 读取该目录下的直接子项(文件或子目录)它 不会自动进入子目录,因此需要你在代码中手动递归。
#include <stdio.h>
#include <dirent.h>
#include <sys/stat.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 fullpath[1024];
snprintf(fullpath, sizeof(fullpath), "%s/%s", path, entry->d_name);
struct stat st;
stat(fullpath, &st);
if (S_ISDIR(st.st_mode)) {
printf("DIR: %s\n", fullpath);
list_dir(fullpath); // 递归
} else {
printf("FILE: %s\n", fullpath);
}
}
closedir(dir);
}
int main() {
list_dir(".");
return 0;
}
可以用:
ftw() / nftw()(标准库,已不推荐)find 命令glob()(仅一层)例如:
find /path -type f
✅ opendir() 只能打开单层目录
❌ 不支持递归
✅ 递归必须 手动实现
如果你是用 C / C++ / Python / Shell,我可以给你对应语言的递归示例。