copendir() 函数用于打开一个目录流,以便使用 readdir() 函数读取目录中的条目
以下是使用 copendir() 遍历目录树的示例代码:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
void traverse_directory_tree(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 statbuf;
if (stat(full_path, &statbuf) == -1) {
perror("stat");
continue;
}
if (S_ISDIR(statbuf.st_mode)) {
printf("Directory: %s\n", full_path);
traverse_directory_tree(full_path);
} else {
printf("File: %s\n", full_path);
}
}
closedir(dir);
}
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <directory>\n", argv[0]);
return EXIT_FAILURE;
}
traverse_directory_tree(argv[1]);
return EXIT_SUCCESS;
}
在这个示例中,traverse_directory_tree() 函数接受一个目录路径作为参数,并使用 opendir() 打开该目录。然后,它使用 readdir() 函数读取目录中的每个条目。对于每个条目,它检查是否为目录(使用 stat() 函数获取文件信息并检查 S_ISDIR() 宏)。如果是目录,它递归地调用 traverse_directory_tree() 函数;否则,它打印文件路径。
要编译并运行此示例,请将其保存为 traverse_directory_tree.c,然后使用以下命令:
gcc -o traverse_directory_tree traverse_directory_tree.c
./traverse_directory_tree /path/to/directory
将 /path/to/directory 替换为您要遍历的目录路径。