在 Debian(其实就是标准 POSIX/Linux C 环境)里,opendir 本身不会递归,它只打开一个目录,返回 DIR *,你需要自己用 readdir + 递归来实现递归遍历。
下面是一个标准、可用的递归遍历目录示例(C 语言):
opendir() 打开目录readdir() 读取目录项. 和 ..)closedir()#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
void list_dir(const char *path) {
DIR *dir;
struct dirent *entry;
struct stat st;
dir = opendir(path);
if (!dir) {
perror("opendir");
return;
}
while ((entry = readdir(dir)) != NULL) {
// 跳过 . 和 ..
if (strcmp(entry->d_name, ".") == 0 ||
strcmp(entry->d_name, "..") == 0)
continue;
// 拼接完整路径
char full_path[1024];
snprintf(full_path, sizeof(full_path), "%s/%s", path, entry->d_name);
// 获取文件信息
if (stat(full_path, &st) == -1) {
perror("stat");
continue;
}
if (S_ISDIR(st.st_mode)) {
printf("目录: %s\n", full_path);
list_dir(full_path); // 递归
} else {
printf("文件: %s\n", full_path);
}
}
closedir(dir);
}
int main(int argc, char *argv[]) {
if (argc < 2) {
fprintf(stderr, "用法: %s <目录>\n", argv[0]);
return 1;
}
list_dir(argv[1]);
return 0;
}
gcc recursive_opendir.c -o recursive_opendir
./recursive_opendir /path/to/dir
readdir 不会递归. 和 .. 必须跳过,否则无限递归stat() 判断是否是目录(不要只看 d_type,某些文件系统不支持)ftw() / nftw()(更简洁)scandir() + 递归lstat + 记录已访问 inode)如果你想要 C++ / Rust / Python 风格,或者 只统计文件数 / 按深度递归,我可以给你对应版本。