copendir在递归遍历中的应用
作者:WeekendFlower
时间:2026-07-29
浏览:0
opendir函数打开目录流,与readdir、closedir配合实现递归遍历。在遍历过程中,跳过当前目录和父目录,通过stat系统调用判断条目类型,对每个子目录递归调用自身,从而逐层列出所有文件和目录,完成目录树的深度优先遍历。
copendir 这个函数,说白了就是用来打开一个目录的。它返回一个指向 DIR 结构的指针,里面装着目录流的信息。在递归遍历目录这种场景里,它通常和 readdir、closedir 搭伙干活——先打开目录,然后挨个读取里面的条目,再判断每个条目是不是子目录。如果是,就递归调用遍历函数,继续往下挖。
下面这段代码,就是一个典型的递归遍历目录的例子:
#include
#include
#include
#include
#include
void list_directory_contents(const char *path) {
DIR *dir;
struct dirent *entry;
struct stat path_stat;
dir = opendir(path);
if (dir == NULL) {
perror("opendir");
return;
}
while ((entry = readdir(dir)) != NULL) {
// Skip current and parent directory entries
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue;
}
// Construct the full path of the entry
char full_path[PATH_MAX];
snprintf(full_path, sizeof(full_path), "%s/%s", path, entry->d_name);
// Get the file status
if (stat(full_path, &path_stat) == -1) {
perror("stat");
continue;
}
// If it's a directory, recurse
if (S_ISDIR(path_stat.st_mode)) {
printf("Directory: %s\n", full_path);
list_directory_contents(full_path);
} else {
// Otherwise, print the file name
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;
}
在这个例子中,list_directory_contents 函数接收一个目录路径作为参数。它先打开目录,然后用 readdir 循环读取每一个条目。针对每个条目,它会调用 stat 获取文件状态,从而判断是文件还是目录。如果是目录,就打印目录名,然后递归调用自身;如果是文件,直接打印文件名。注意,这里跳过了当前目录(.)和父目录(..)这两个特殊条目,不然递归会陷入死循环。
用起来也很简单:把代码编译成可执行文件,然后在命令行里指定要遍历的目录路径就行。比如:
gcc -o listdir listdir.c
./listdir /path/to/directory
这样,程序就会递归地列出指定目录下所有文件和子目录,一层层展示出来。
作者最新文章
赤友清理大师
2026-09-16 17:43
南邮光擎智算团队:GaN基Micro-LED光计算芯片从理论到流片的突破
2026-09-08 18:35
多张照片怎么合成PDF文件?三种图片转PDF工具怎么选?
2026-09-03 17:04
Excel转PDF防乱版指南:在线与本地双方案及排版检查
2026-09-03 10:04
多个PDF怎么合并成一个?合并后顺序怎么检查?
2026-09-02 19:54
热门文章
更多
精品专题
更多
Mac软件
更多
WINDOWS
更多

































