copendir 是一个用于打开目录的函数,通常与 readdir 和 closedir 一起使用来遍历目录中的文件和子目录。要实现目录树的遍历,你需要递归地访问每个子目录,并对其中的文件和子目录执行相同的操作。
以下是一个使用 copendir、readdir 和 closedir 实现目录树遍历的示例代码(C语言):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>
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 statbuf;
if (stat(full_path, &statbuf) == -1) {
perror("stat");
continue;
}
if (S_ISDIR(statbuf.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 <directory>\n", argv[0]);
return EXIT_FAILURE;
}
list_directory_contents(argv[1]);
return EXIT_SUCCESS;
}
这个程序接受一个目录路径作为命令行参数,并递归地列出该目录及其所有子目录中的文件和子目录。注意,这个示例代码没有处理符号链接,可能会导致无限循环。在实际应用中,你可能需要添加额外的逻辑来处理符号链接。