在 Debian(或者说 Linux 下 C/C++ 编程)里,readdir 本身只能读取一个目录下的条目,不支持递归。要实现“递归读取目录”,需要自己写递归函数,在碰到子目录时再次调用 readdir。
下面给你几种常见做法。
opendir + readdir + 递归(最基础)#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.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[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(int argc, char *argv[]) {
if (argc < 2) {
printf("Usage: %s <dir>\n", argv[0]);
return 1;
}
list_dir(argv[1]);
return 0;
}
gcc readdir_recursive.c -o readdir_recursive
./readdir_recursive /path/to/dir
nftw(推荐,系统自带)Debian 自带 nftw(),专门用来递归遍历目录树,比手写递归安全。
#define _XOPEN_SOURCE 500
#include <stdio.h>
#include <ftw.h>
int cb(const char *path, const struct stat *st, int flag, struct FTW *ftwbuf) {
if (flag == FTW_D)
printf("DIR : %s\n", path);
else if (flag == FTW_F)
printf("FILE: %s\n", path);
return 0;
}
int main(int argc, char *argv[]) {
nftw(argv[1], cb, 20, FTW_PHYS);
return 0;
}
如果只是“用 Debian 递归列目录”:
find /path/to/dir
或
ls -R /path/to/dir
readdir 不区分文件/目录
stat() 或 lstat() 判断lstat 避免死循环opendir 可能返回 NULL如果你告诉我:
我可以给你更精确的递归实现。