copendir 是一个用于打开目录的函数,而不是直接用于遍历目录结构的。要遍历 Linux 目录结构,你需要结合使用 opendir、readdir 和 closedir 函数。下面是一个简单的示例,展示了如何使用这些函数遍历目录结构:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
void traverse_directory(const char *path) {
DIR *dir;
struct dirent *entry;
struct stat statbuf;
dir = opendir(path);
if (dir == NULL) {
perror("opendir");
return;
}
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);
// 获取文件信息
if (stat(full_path, &statbuf) == -1) {
perror("stat");
continue;
}
// 判断是否为目录
if (S_ISDIR(statbuf.st_mode)) {
// 递归遍历子目录
traverse_directory(full_path);
} else {
// 输出文件名
printf("%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(argv[1]);
return EXIT_SUCCESS;
}
这个程序接受一个目录作为命令行参数,并递归地遍历该目录及其子目录中的所有文件。对于每个文件,它将输出文件的完整路径。请注意,这个程序不包括错误处理的所有细节,因此在实际应用中可能需要添加更多的错误检查和处理。