在 Debian(以及所有类 Unix 系统)里,opendir() 本身不能递归读取目录。
opendir():只打开一个目录readdir():只读取该目录下的条目(不进入子目录)典型递归读取目录的方式是:
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>
#include <stdio.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 full[1024];
snprintf(full, sizeof(full), "%s/%s", path, entry->d_name);
struct stat st;
stat(full, &st);
if (S_ISDIR(st.st_mode)) {
list_dir(full); // 递归
} else {
printf("%s\n", full);
}
}
closedir(dir);
}
nftw()(标准库,递归遍历)#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(".", cb, 20, FTW_PHYS);
}
find 命令(非 C 程序)find /path -type f
| 函数 | 是否递归 |
|---|---|
opendir |
❌ 否 |
readdir |
❌ 否 |
nftw |
✅ 是 |
find |
✅ 是 |
如果你是 写 C 程序 / shell 脚本 / 内核模块,可以告诉我具体使用场景,我可以给你更合适的方案。