copirdir
函数用于递归地复制一个目录及其内容到另一个位置。它在某些系统上可用,但并不是所有平台都支持。在支持的系统上,它的原型通常如下:
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
int copirdir(const char *src, const char *dest);
下面是一个简单的示例,展示如何使用 copirdir
函数来复制目录:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
int copirdir(const char *src, const char *dest) {
DIR *dir;
struct dirent *entry;
struct stat statbuf;
char path[1024];
// 打开源目录
if (!(dir = opendir(src))) {
perror("opendir");
return -1;
}
// 创建目标目录
if (mkdir(dest, statbuf.st_mode) == -1) {
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 (copirdir(path, dest) == -1)
return -1;
} else {
// 如果是文件,使用标准库函数复制
FILE *src_file = fopen(path, "rb");
FILE *dest_file = fopen(dest, "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) {
if (fwrite(buffer, 1, n, dest_file) != n) {
perror("fwrite");
fclose(src_file);
fclose(dest_file);
closedir(dir);
return -1;
}
}
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;
}
if (copirdir(argv[1], argv[2]) == 0) {
printf("Directory copied successfully.
");
} else {
fprintf(stderr, "Failed to copy directory.
");
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
编译程序:使用 gcc
编译上述代码。
gcc -o copirdir_example copirdir_example.c
运行程序:提供源目录和目标目录作为参数。
./copirdir_example /path/to/source /path/to/destination
请注意,copirdir
不是标准的 POSIX 函数,因此在某些系统上可能不可用。如果你需要跨平台的解决方案,可以考虑使用其他库或工具,如 librsync
或 rsync
命令行工具。