在 Ubuntu(Linux)下,如果你想递归遍历子目录,通常不是用 opendir 一个函数完成的,而是 opendir + readdir + 递归调用 来实现。
下面给你一个完整、可运行的 C 语言示例,演示如何用 opendir / readdir 递归遍历目录。
opendir() 打开目录readdir() 读取目录项. 和 ..),递归调用自己#include <stdio.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <unistd.h>
void list_dir(const char *path) {
DIR *dir = opendir(path);
if (!dir) {
perror("opendir");
return;
}
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
// 跳过 . 和 ..
if (strcmp(entry->d_name, ".") == 0 ||
strcmp(entry->d_name, "..") == 0)
continue;
// 构造完整路径
char full_path[1024];
snprintf(full_path, sizeof(full_path), "%s/%s", path, entry->d_name);
// 获取文件信息
struct stat st;
if (stat(full_path, &st) == -1) {
perror("stat");
continue;
}
if (S_ISDIR(st.st_mode)) {
printf("目录: %s\n", full_path);
list_dir(full_path); // 递归子目录
} else {
printf("文件: %s\n", full_path);
}
}
closedir(dir);
}
int main(int argc, char *argv[]) {
if (argc < 2) {
printf("用法: %s <目录>\n", argv[0]);
return 1;
}
list_dir(argv[1]);
return 0;
}
gcc recursive_ls.c -o recursive_ls
./recursive_ls /path/to/dir
opendir 只能打开一层目录entry->d_type 也可判断类型(但不是所有文件系统都支持)nftw()(不推荐初学时用)find /path/to/dir
如果你是 C / C++ / shell / Python 哪种方式想递归目录,我可以按你的需求再细化。