在 Ubuntu(Linux)下,如果你想递归遍历目录(包括子目录),常见做法有几种,取决于你用的是 Shell 命令 还是 C 语言 readdir()。
findfind /path/to/dir -type f
递归列出所有文件。
find /path/to/dir -type d
递归列出所有目录。
ls -Rls -R /path/to/dir
readdir 递归子目录(重点)readdir() 本身不会递归,需要你自己写递归函数。
opendir() 打开目录readdir() 读取每一项. 和 ..)#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.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 fullpath[1024];
snprintf(fullpath, sizeof(fullpath), "%s/%s", path, entry->d_name);
struct stat st;
stat(fullpath, &st);
if (S_ISDIR(st.st_mode)) {
printf("DIR: %s\n", fullpath);
list_dir(fullpath); // 递归
} else {
printf("FILE: %s\n", fullpath);
}
}
closedir(dir);
}
int main() {
list_dir(".");
return 0;
}
gcc readdir_recursive.c -o readdir_recursive
./readdir_recursive
readdir 为什么不能自动递归?readdir() 只读取当前目录项lstat(fullpath, &st);
if (S_ISLNK(st.st_mode)) continue;
| 场景 | 推荐 |
|---|---|
| 命令行 | find |
| C 程序 | opendir + readdir + 递归 |
| 高性能 | nftw() |
如果你需要 C++ / nftw / 过滤特定文件类型 的示例,也可以告诉我。