在 Ubuntu / Linux 下,opendir() 本身不能递归子目录。
opendir() 只是打开一个目录,返回一个 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)) {
printf("Dir: %s\n", full);
list_dir(full); // 递归子目录
} else {
printf("File: %s\n", full);
}
}
closedir(dir);
}
opendir / readdir 是 POSIX APIfind path
或ls -R path
如果你是在写 C / C++ 程序 或 脚本,可以告诉我具体场景,我可以给你更合适的示例。