在 Debian(以及其它 Linux 系统)里,opendir() 本身不能递归,它只能打开一个目录,返回一个 DIR *,供你用 readdir() 读取该目录下的条目。
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)) {
printf("目录: %s\n", full);
list_dir(full); // 递归
} else {
printf("文件: %s\n", full);
}
}
closedir(dir);
}
find /path -type dstd::filesystem::recursive_directory_iteratoros.walk()ls -R✅ opendir() 是递归遍历的基础工具
❌ 但它不具备递归能力
✅ 递归逻辑必须由程序员实现
如果你是在写 C / C++ 程序,或者想用某个具体语言实现递归目录遍历,可以告诉我。