在 Linux 下使用 readdir 进行递归遍历目录,核心思路是:
opendir 打开目录readdir 读取目录项. 和 ..stat / lstat 判断是否是目录closedir 关闭目录#include <stdio.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 fullpath[1024];
snprintf(fullpath, sizeof(fullpath), "%s/%s", path, entry->d_name);
struct stat st;
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) {
printf("usage: %s <dir>\n", argv[0]);
return 1;
}
list_dir(argv[1]);
return 0;
}
readdir 只读取目录项stat() 或 lstat()lstat:不会跟随符号链接stat:会跟随符号链接(可能死循环)避免递归符号链接目录:
lstat(fullpath, &st);
if (S_ISLNK(st.st_mode)) {
// 符号链接,不递归
}
if (lstat(fullpath, &st) == 0 && S_ISDIR(st.st_mode)) {
if (!S_ISLNK(st.st_mode)) {
list_dir(fullpath);
}
}
readdir 本身不支持递归. / ..lstat + 判断 S_ISDIR如果你需要:
find 的功能可以继续问我。