在 CentOS(Linux) 下,readdir 本身只读取一个目录,不会自动递归。
如果要递归遍历目录,必须在代码中自己实现递归或队列遍历。
下面按常见场景给你说明。
readdir 用来读取 单个目录 中的文件和子目录:
DIR *dir = opendir(path);
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
// 处理 entry->d_name
}
closedir(dir);
但它 不会进入子目录。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>
void list_dir(const char *path) {
DIR *dir = opendir(path);
if (!dir) 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;
stat(fullpath, &st);
if (S_ISDIR(st.st_mode)) {
// 是目录,递归
printf("DIR: %s\n", fullpath);
list_dir(fullpath);
} else {
printf("FILE: %s\n", fullpath);
}
}
closedir(dir);
}
int main() {
list_dir(".");
return 0;
}
✅ 编译:
gcc readdir_recursive.c -o readdir_recursive
lstat(fullpath, &st);
if (S_ISLNK(st.st_mode)) {
printf("LINK: %s\n", fullpath);
continue;
}
find /path/to/dir
或
ls -R /path/to/dir
| 问题 | 说明 |
|---|---|
| readdir 能递归吗 | ❌ 不能 |
| 怎么递归 | ✅ 自己用 readdir + 递归 / 队列 |
| C 是否支持 | ✅ POSIX 标准 |
| CentOS 专用 | ❌ 通用 Linux |
如果你有 具体场景(例如:只统计文件、过滤后缀、避免某些目录、C++ / Python),可以告诉我,我可以给你更贴合的示例。