在 Linux 下使用 readdir 递归遍历目录,本质上是自己写递归函数,因为 readdir 本身只负责“读一个目录里的条目”,不支持递归。
下面给你一个标准、可运行、安全的示例(C 语言)。
opendir() 打开目录readdir() 逐个读取目录项. 和 ..stat() 判断是否是目录#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.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("[DIR] %s\n", full_path);
list_dir(full_path); // 递归
} else {
printf("[FILE] %s\n", full_path);
}
}
closedir(dir);
}
int main(int argc, char *argv[]) {
if (argc < 2) {
fprintf(stderr, "Usage: %s <dir>\n", argv[0]);
return 1;
}
list_dir(argv[1]);
return 0;
}
gcc readdir_recursive.c -o readdir_recursive
./readdir_recursive /path/to/dir
readdir 只给文件名必须自己拼路径:
path + "/" + entry->d_name
stat,不要用 d_typed_type 在某些文件系统(如 NFS)不可靠。
如果想安全一点:
if (S_ISLNK(st.st_mode)) {
// 跳过或特殊处理
}
std::filesystem::recursive_directory_iteratorfindos.walk如果你需要:
nftw() 替代 readdir告诉我你的具体需求,我可以直接给你对应版本。