copirdir 函数用于复制目录及其内容。它通常在 POSIX 兼容的系统上可用,例如 Linux 和 macOS。该函数会递归地复制源目录中的所有文件和子目录到目标目录。
以下是一个使用 copirdir 函数的简单示例:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
// 递归复制目录
int copy_directory(const char *src, const char *dest) {
DIR *dir = opendir(src);
struct dirent *entry;
struct stat statbuf;
char path[1024];
// 检查源目录是否可以打开
if (!dir) {
perror("opendir");
return -1;
}
// 创建目标目录
if (mkdir(dest, statbuf.st_mode) == -1) {
if (errno != EEXIST) {
perror("mkdir");
closedir(dir);
return -1;
}
}
// 遍历目录中的每个条目
while ((entry = readdir(dir)) != NULL) {
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
continue;
// 构建完整路径
snprintf(path, sizeof(path), "%s/%s", src, entry->d_name);
// 获取文件信息
if (stat(path, &statbuf) == -1) {
perror("stat");
closedir(dir);
return -1;
}
// 如果是目录,递归复制
if (S_ISDIR(statbuf.st_mode)) {
if (copy_directory(path, dest) == -1)
return -1;
} else {
// 如果是普通文件,直接复制
FILE *src_file = fopen(path, "rb");
FILE *dest_file = fopen(dest_path, "wb");
if (!src_file || !dest_file) {
perror("fopen");
closedir(dir);
return -1;
}
char buffer[1024];
size_t n;
while ((n = fread(buffer, 1, sizeof(buffer), src_file)) > 0) {
fwrite(buffer, 1, n, dest_file);
}
fclose(src_file);
fclose(dest_file);
}
}
closedir(dir);
return 0;
}
int main(int argc, char *argv[]) {
if (argc != 3) {
fprintf(stderr, "Usage: %s <source_directory> <destination_directory>
", argv[0]);
return EXIT_FAILURE;
}
const char *src_dir = argv[1];
const char *dest_dir = argv[2];
if (copy_directory(src_dir, dest_dir) == 0) {
printf("Directory copied successfully.
");
} else {
fprintf(stderr, "Failed to copy directory.
");
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
opendir:打开一个目录流。readdir:读取目录中的下一个条目。stat:获取文件或目录的信息。mkdir:创建一个新的目录。fopen, fread, fwrite, fclose:用于文件的读写操作。copirdir 不是标准 C 库函数,而是某些系统特定的扩展。在标准 POSIX 中,通常使用 cp -r 命令行工具来复制目录。