不多说直接上代码
#include <myhead.h>
int copy_part(int file1, int file2, int start, int end)
{
// 置位光标
off_t bytes_read = start;
// 定义缓冲区用于数据读写
char buf[128];
lseek(file1, start, SEEK_SET);
lseek(file2, start, SEEK_SET);
// 读取源文件
while (bytes_read < end)
{
int count = read(file1, buf, sizeof(buf));
if (count <= 0)
return 0;
// 写目标文件
write(file2, buf, count);
bytes_read += count;
}
}
int main(int argc, char *argv[])
{
// 检查命令行参数数量是否正确
if (argc != 3)
{
printf("使用方法: %s <源文件> <目标文件>\n", argv[0]);
return EXIT_FAILURE;
}
// 打开两个文件
int source_fd = -1, copy_fd = -1;
source_fd = open(argv[1], O_RDONLY);
copy_fd = open(argv[2], O_WRONLY | O_CREAT | O_TRUNC, 0777);
// 检查文件打开是否成功
if (source_fd == -1 || copy_fd == -1)
{
printf("文件打开失败\n");
return EXIT_FAILURE;
}
// 获取源文件大小
int file_size = lseek(source_fd, 0, SEEK_END);
int half_size = file_size / 2;
// 创建子进程
pid_t pid = fork();
// 检查子进程创建是否成功
if (pid == -1)
{
close(source_fd);
close(copy_fd);
perror("线程创建失败\n");
return EXIT_FAILURE;
}
// 父进程将文件的前一半数据写入到新文件中
if (pid > 0)
{
copy_part(source_fd, copy_fd, 0, half_size);
}
// 子进程将文件的后一半数据写入到新文件中
else
{
copy_part(source_fd, copy_fd, half_size, file_size);
}
// 父进程等待子进程结束
if (pid > 0)
wait(NULL);
printf("拷贝成功\n");
// 关闭文件
close(source_fd);
close(copy_fd);
}
运行结果
./copy copy.c copy.txt
拷贝成功
拷贝成功