在 Debian(以及所有符合 POSIX 标准的系统)里,opendir 本身不能遍历子目录,它只能打开一个目录,并配合 readdir 读取该目录下的直接条目(包括子目录名,但不会自动进入子目录)。
opendir(dir):打开一个目录readdir(dp):读取目录项(文件 / 子目录 / 符号链接等)opendir#include <dirent.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
void walk(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)) {
printf("DIR: %s\n", full);
walk(full); // 递归遍历子目录
} else {
printf("FILE: %s\n", full);
}
}
closedir(dir);
}
int main() {
walk(".");
return 0;
}
find /path:递归遍历ls -R:递归列出✅ opendir 可以“看到”子目录
❌ opendir 不会自动遍历子目录
✅ 遍历子目录必须手动递归
如果你是在写 C / C++ / shell / Python,可以告诉我语言,我可以给你更合适的示例。