使用copendir进行递归目录遍历
作者:暮色微凉
时间:2026-07-12
浏览:0
在C语言中,通过opendir打开目录流,结合readdir读取目录项,跳过“.”和“..”,利用stat和S_ISDIR判断是否为目录,若是目录则递归调用遍历函数,否则输出文件路径。最终输出所有文件与子目录的完整路径,实现整个目录树的深度优先遍历。
在C语言里,opendir这个函数的作用是打开一个目录流——说白了就是让你能“看”那个文件夹里面的东西。但它自己可不会递归往下翻,要想把子目录里的文件也统统找出来,还得手动搭配readdir,逐个判断每个条目是不是目录,如果是,就再调一遍遍历函数。

下面这段代码,就是C语言里实现递归目录遍历的经典写法:
#include
#include
#include
#include
#include
void list_directory_contents(const char *path) {
DIR *dir = opendir(path);
if (dir == NULL) {
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[PATH_MAX];
snprintf(full_path, sizeof(full_path), "%s/%s", path, entry->d_name);
struct stat path_stat;
if (stat(full_path, &path_stat) == -1) {
perror("stat");
continue;
}
if (S_ISDIR(path_stat.st_mode)) {
printf("Directory: %s\n", full_path);
list_directory_contents(full_path); // 递归调用
} else {
printf("File: %s\n", full_path);
}
}
closedir(dir);
}
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s \n", argv[0]);
return EXIT_FAILURE;
}
list_directory_contents(argv[1]);
return EXIT_SUCCESS;
}
说明:
opendir:先打开目录流,拿到一个DIR *指针。如果返回NULL,说明路径有问题,直接报错退出。readdir:用readdir一次次读下一个条目,直到读完。要注意跳过.和..这两个特殊目录,否则会陷入无限循环。stat:拿到每个条目的详细信息,存在struct stat里。用S_ISDIR宏判断是不是目录。- 递归:如果是目录,就把完整路径传给
list_directory_contents继续往下走;如果是文件,直接打印名字。
编译和运行:
gcc -o listdir listdir.c
./listdir /path/to/directory
把上面代码保存成 listdir.c,用 gcc 编译,然后带上目标目录路径运行,就能看到它把所有子目录和文件的完整路径列出来了。整个过程很直接,但别忘了处理路径拼接和递归退出条件——不然很容易出 bug。
作者最新文章
Photoshop文字外框怎么设置?给文字加边框的实用方法
2026-09-22 16:12
白描 PDF
2026-09-16 17:44
密码键盘
2026-09-16 17:43
3dmax快捷键失效了怎么办
2026-09-16 13:53
Xiaomi 18 Fold首销数据解读:较上代大折叠增长310%的原因与配置分析
2026-09-08 16:55
热门文章
更多
精品专题
更多
Mac软件
更多
WINDOWS
更多


































