#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <pthread.h>
#define BUFFER_SIZE 128
struct ThreadArgs {
const char *srcfile;
const char *dstfile;
int start;
int len;
};
int get_file_len(const char *srcfile) {
int srcfd;
if ((srcfd = open(srcfile, O_RDONLY)) == -1) {
perror("打开源文件错误");
return -1;
}
int len = lseek(srcfd, 0, SEEK_END);
close(srcfd);
return len;
}
void *file_copy(void *args) {
struct ThreadArgs *threadArgs = (struct ThreadArgs *)args;
int srcfd, dstfd;
if ((srcfd = open(threadArgs->srcfile, O_RDONLY)) == -1) {
perror("打开源文件错误");
pthread_exit(NULL);
}
if ((dstfd = open(threadArgs->dstfile, O_WRONLY)) == -1) {
perror("打开目标文件错误");
close(srcfd);
pthread_exit(NULL);
}
lseek(srcfd, threadArgs->start, SEEK_SET);
lseek(dstfd, threadArgs->start, SEEK_SET);
char buf[BUFFER_SIZE];
int res, sum = 0;
while (1) {
res = read(srcfd, buf, sizeof(buf));
sum += res;
if (sum >= threadArgs->len || res == 0) {
write(dstfd, buf, res - (sum - threadArgs->len));
break;
}
write(dstfd, buf, res);
}
close(srcfd);
close(dstfd);
pthread_exit(NULL);
}
int main(int argc, const char *argv[]) {
if (argc != 3) {
printf("输入文件错误\n");
printf("用法:./a.out 源文件 目标文件\n");
return -1;
}
int len = get_file_len(argv[1]);
pthread_t thread1, thread2;
struct ThreadArgs args1 = {argv[1], argv[2], 0, len / 2};
struct ThreadArgs args2 = {argv[1], argv[2], len / 2, len - len / 2};
if (pthread_create(&thread1, NULL, file_copy, (void *)&args1) != 0) {
perror("创建线程错误");
return -1;
}
if (pthread_create(&thread2, NULL, file_copy, (void *)&args2) != 0) {
perror("创建线程错误");
return -1;
}
if (pthread_join(thread1, NULL) != 0 || pthread_join(thread2, NULL) != 0) {
perror("等待线程错误");
return -1;
}
printf("拷贝成功\n");
return 0;
}
![在这里插入图片描述](https://img-blog.csdnimg.cn/direct/277673377a2145acbd88c748121716ee.png#pic_center)