在 CentOS(Linux) 里,readdir 本身是 不递归的,它只读取当前目录下的条目。要实现“递归读取目录”,通常是:
readdir + 递归调用
下面给你几种常见做法(C 语言 / shell / find)。
opendir() 打开目录readdir() 读取每一项DT_DIR),并且不是 . 和 ..,就递归调用#include <stdio.h>
#include <dirent.h>
#include <string.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);
if (entry->d_type == DT_DIR) {
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;
}
gcc readdir_recursive.c -o readdir_recursive
./readdir_recursive /path/to/dir
如果你只是想在 CentOS 上递归列目录,不用写 C:
find /path/to/dir
或只列目录:
find /path/to/dir -type d
nftw(更专业,C 语言)如果你不想自己写递归,可以用标准库:
#include <ftw.h>
#include <stdio.h>
int cb(const char *path, const struct stat *st, int type, struct FTW *ftw) {
printf("%s\n", path);
return 0;
}
int main() {
nftw("/path/to/dir", cb, 20, 0);
return 0;
}
readdir 为什么不能递归?readdir 只读取一个目录DT_LNK 需要处理,否则可能死循环stat() 判断真实类型如果你说的是:
告诉我,我可以给你更针对性的示例。