在 Ubuntu(Linux)下,readdir 本身只能读取一个目录的内容,不会自动递归。要实现“递归目录”,需要:
opendir + readdir 读取目录d_type 或 stat 是否是目录下面给你一个标准 C 语言示例(最贴近你问的 readdir)。
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
void list_dir(const char *path) {
DIR *dir = opendir(path);
if (!dir) {
perror("opendir");
return;
}
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
// 跳过 . 和 ..
if (strcmp(entry->d_name, ".") == 0 ||
strcmp(entry->d_name, "..") == 0)
continue;
// 拼接完整路径
char fullpath[4096];
snprintf(fullpath, sizeof(fullpath), "%s/%s", path, entry->d_name);
// 判断是否是目录
struct stat st;
if (stat(fullpath, &st) == -1) {
perror("stat");
continue;
}
if (S_ISDIR(st.st_mode)) {
printf("DIR: %s\n", fullpath);
list_dir(fullpath); // 递归
} else {
printf("FILE: %s\n", fullpath);
}
}
closedir(dir);
}
int main(int argc, char *argv[]) {
if (argc < 2) {
printf("Usage: %s <dir>\n", argv[0]);
return 1;
}
list_dir(argv[1]);
return 0;
}
gcc recursive_readdir.c -o recursive_readdir
./recursive_readdir /path/to/dir
readdir() 只返回一个目录项d_type 有时不可靠(某些文件系统)stat() 更通用必须跳过:
.
..
find /path/to/dir
# 或
ls -R /path/to/dir
也可以用 <filesystem>(C++17):
#include <filesystem>
namespace fs = std::filesystem;
for (auto& p : fs::recursive_directory_iterator("/path")) {
std::cout << p.path() << "\n";
}
如果你想要:
告诉我,我可以继续给你写。