在 Debian(以及其它 Linux 系统)里,opendir 本身不能递归遍历目录。
opendir():只是打开一个目录,返回一个 DIR *readdir():读取该目录下的直接成员(文件和子目录)常见做法:
opendir + readdirstat / lstatopendir(递归或栈/队列)#include <dirent.h>
#include <sys/stat.h>
#include <stdio.h>
#include <string.h>
void traverse(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;
lstat(full, &st);
if (S_ISDIR(st.st_mode)) {
printf("DIR: %s\n", full);
traverse(full); // 递归
} else {
printf("FILE: %s\n", full);
}
}
closedir(dir);
}
int main() {
traverse(".");
return 0;
}
findfts_open / nftw(比手写递归更安全)
opendir只能打开一层目录,递归遍历必须自己实现或用更高层 API。
如果你是想问 shell / Python / find 命令 的递归,也可以告诉我。