发布于2026-07-29 阅读(0)
扫一扫,手机访问
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
这样,程序就会递归地列出指定目录下所有文件和子目录,一层层展示出来。
上一篇:copendir在多线程中的应用
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
8