在 Ubuntu(Linux)下,如果你说的是 用 C 语言调用 readdir 实现递归遍历目录,核心思路是:
opendir→readdir→ 如果是目录就递归readdir
下面给你一个完整、可运行的递归示例。
readdir 递归遍历目录#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>
void list_dir(const char *path) {
DIR *dir;
struct dirent *entry;
struct stat st;
dir = opendir(path);
if (!dir) {
perror("opendir");
return;
}
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);
// 获取文件信息
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) {
fprintf(stderr, "用法: %s <目录>\n", argv[0]);
return 1;
}
list_dir(argv[1]);
return 0;
}
gcc readdir_recursive.c -o readdir_recursive
./readdir_recursive /path/to/dir
readdir 不会递归readdir 只读取当前目录. 和 ..否则会无限递归:
if (strcmp(entry->d_name, ".") == 0 ||
strcmp(entry->d_name, "..") == 0)
continue;
stat / lstat 判断目录S_ISDIR(st.st_mode) 判断是否是目录lstatfind /path/to/dir
#include <filesystem>
for (auto &p : std::filesystem::recursive_directory_iterator("/path"))
std::cout << p.path() << "\n";
如果你是想:
可以告诉我,我可以直接按你的使用场景写。