在 Debian(以及一般 Linux/Unix 系统)里,opendir 本身不能递归。
opendir 是什么opendir 是 POSIX / C 标准库函数:
DIR *opendir(const char *name);
它的作用只是打开一个目录,返回一个 DIR * 句柄,用于后续 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);
}
如果你不是在写 C 程序,而是想在 shell 里递归:
find /path -type d
或
ls -R /path
nftw()(标准库,支持递归)fts_open()(BSD/Linux)std::filesystem::recursive_directory_iteratoropendir 不能递归,只能打开单层目录;递归需要你自己用 readdir + 递归实现。
如果你是在写 C / C++ 程序,或者只是想在 Debian 上“递归列目录”,可以告诉我具体场景,我可以给你更合适的方案。