在 Ubuntu(Linux)下,opendir 本身不能递归遍历子目录,它只能打开并读取某一个目录里的条目(文件和子目录名)。
具体说明如下:
opendir 的作用DIR *opendir(const char *name);
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 能打开目录opendir 不会自动进入子目录opendir + readdir + stat + 递归如果你愿意,我也可以给你一个 不用递归的栈/队列实现,或者 用 nftw 更简单的方法。