在 Linux 下使用 readdir 递归遍历目录,核心思路就是:
opendir → readdir → 如果是目录就递归调用自己,如果是文件就处理。
下面给你一个 C 语言示例,标准 POSIX 接口(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;
struct dirent *entry;
struct stat st;
char fullpath[1024];
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;
snprintf(fullpath, sizeof(fullpath), "%s/%s", path, entry->d_name);
if (stat(fullpath, &st) == -1) {
perror("stat");
continue;
}
if (S_ISDIR(st.st_mode)) {
printf("DIR: %s\n", fullpath);
list_dir(fullpath); // 递归
} else {
printf("FILE: %s\n", fullpath);
}
}
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;
}
stat 而不是 entry->d_typeentry->d_type 不一定可靠(某些文件系统返回 DT_UNKNOWN)stat() 是最通用的方式. 和 ..否则会无限递归
如果你不想递归,可以用:
fts_open / fts_read(推荐)nftw()需要我给你 非递归版本 或 C++ / Rust 示例 吗?