在 Debian(以及一般 Linux/Unix 系统) 里,你提到的 copendir 应该是指 opendir / readdir 这套目录遍历 API(POSIX 标准,C 语言)。
先给结论:
opendir+readdir本身不能递归遍历目录,只能遍历“当前一层目录”。
要递归遍历,必须自己在代码里写递归逻辑。
opendir / readdir 的能力边界DIR *dir = opendir(path);
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
// 只能看到当前目录下的文件和子目录名
}
closedir(dir);
opendir 打开目录readdir 读取每一项. / ..):
#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);
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;
}
如果你不想自己写递归:
ftw / nftw(标准库,已支持递归)#include <ftw.h>
int cb(const char *path, const struct stat *st, int type) {
printf("%s\n", path);
return 0;
}
int main() {
nftw(".", cb, 20, FTW_DEPTH);
}
find /path -type f
| 方式 | 是否递归 | 说明 |
|---|---|---|
opendir + readdir |
❌ | 手动递归 |
| 自己写递归 | ✅ | 最常见 |
nftw |
✅ | 推荐 |
find |
✅ | 非编程场景 |
如果你是:
可以告诉我,我可以给你更针对性的示例。