在 Debian(以及一般的 Linux)下,如果你问的是 readdir 这个函数如何递归遍历子目录,通常是指 C 语言中的 readdir() + opendir() / stat() 来实现递归目录遍历。
下面给你几种常见做法。
readdir 递归)opendir() 打开目录readdir() 逐个读取目录项stat() 或 lstat() 判断是否为目录. 或 ..,递归调用自己#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) 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(int argc, char *argv[]) {
list_dir(argv[1]);
return 0;
}
编译:
gcc readdir_recursive.c -o readdir_recursive
./readdir_recursive /path/to/dir
stat() 会跟随符号链接lstat()lstat(fullpath, &st);
if (S_ISLNK(st.st_mode)) {
// 符号链接
}
ftw() 或 nftw()(更专业)nftw()(推荐)#include <ftw.h>
#include <stdio.h>
int fn(const char *path, const struct stat *st, int flag, struct FTW *ftwbuf) {
printf("%s\n", path);
return 0;
}
int main() {
nftw(".", fn, 20, FTW_PHYS);
return 0;
}
如果你只是想在 Debian 上递归列目录:
find /path -type f
ls -R /path
| 方法 | 是否递归 | 推荐度 |
|---|---|---|
readdir + 递归 |
✅ | ⭐⭐⭐ |
nftw |
✅ | ⭐⭐⭐⭐⭐ |
find |
✅ | ⭐⭐⭐⭐⭐ |
如果你是想 写内核模块 / 使用 readdir 系统调用 / 在某个特定语言(Python/Shell)里递归,可以告诉我具体场景。