在 Debian(或任何 Linux 系统)下,使用 C 语言通过 opendir / readdir 遍历子目录(递归遍历目录树),核心思路是:
opendir() 打开目录readdir() 读取每一项d_type 或 stat() 是否为目录#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) {
perror("opendir");
return;
}
struct dirent *entry;
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 (entry->d_type == DT_DIR) {
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 listdir.c -o listdir
./listdir /path/to/dir
d_type 不一定可靠在某些文件系统(如某些 NFS)上:
entry->d_type == DT_UNKNOWN
✅ 更稳妥的方式是用 stat():
struct stat st;
stat(full_path, &st);
if (S_ISDIR(st.st_mode)) {
list_dir(full_path);
}
避免死循环:
lstat(full_path, &st);
if (S_ISLNK(st.st_mode)) {
// 跳过符号链接目录
}
真实项目建议用 realpath() 或动态分配路径。
如果你不想用递归,可以用:
fts_open()(更专业,推荐)#include <fts.h>
适合大规模目录遍历。
✅ Debian 下用 opendir 遍历子目录 =
opendir → readdir → 判断目录 → 递归
如果你需要:
nftw()可以继续问我。