#include <head.h>
struct File //创建结构体
{
int cont;
int len;
int fd;
int fb;
};
int get_file_len(const char* srcfile,const char* destfile) //获取文件字符串长度
{
int fd=open(srcfile,O_RDONLY);//只读
if(fd==-1)
{
perror("open error");
return -1;
}
int fb=open(destfile,O_CREAT|O_WRONLY|O_TRUNC,0664);//创建,只写文件
if(fb==-1)
{
perror("open error");
return -1;
}
int size=lseek(fd,0,SEEK_END);
close(fd);
close(fb);
return size;//返回
}
void *task(void *arg)
{
char buf[1280]="";
int sum=0;
if((*((struct File*)arg)).cont==1)//结构体中cont为两个进程的区别标志
{
while(1){
lseek((*((struct File*)arg)).fd,0,SEEK_SET);//移动光标位置
lseek((*((struct File*)arg)).fb,0,SEEK_SET);
int res=read((*((struct File*)arg)).fd,buf,sizeof(buf));//存储字符串
sum+=res;//计算已存储字符串长度
if(res==0||sum>(*((struct File*)arg)).len)//当前半段存储完毕或超出一半
{
write((*((struct File*)arg)).fb,buf,res-(sum-(*((struct File*)arg)).len));
break;
}
write(((*((struct File*)arg)).fb),buf,res);//存入fb
}
pthread_exit(NULL);//退出线程
}else if((*((struct File*)arg)).cont==2)
{
while(1){
lseek((*((struct File*)arg)).fd,(*((struct File*)arg)).len/2,SEEK_SET);
lseek((*((struct File*)arg)).fb,(*((struct File*)arg)).len/2,SEEK_SET);
int res=read((*((struct File*)arg)).fd,buf,sizeof(buf));
sum+=res;
if(res==0||sum>((*((struct File*)arg)).len-(*((struct File*)arg)).len/2))
{
write((*((struct File*)arg)).fb,buf,res-(sum-((*((struct File*)arg)).len-(*((struct File*)arg)).len/2)));
break;
}
write(((*((struct File*)arg)).fb),buf,res);
}
pthread_exit(NULL);
}
}
int main(int argc, char const *argv[])
{
if(argc!=3)//判断传入文件是否为3
{
printf("input file error\n");
return -1;
}
int len=get_file_len(argv[1],argv[2]);//获取fd字符串长度
int fd=open(argv[1],O_RDONLY);//只读
int fb=open(argv[2],O_WRONLY);//只写
struct File file={1,len/2,fd,fb};//创建两个结构体 cont不同 len不同
struct File file1={2,len,fd,fb};
pthread_t tid1,tid2;
if(pthread_create(&tid1,NULL,task,&file)!=0)//双线程
{
printf("tid1 创建失败\n");
return -1;
}
if(pthread_create(&tid2,NULL,task,&file1)!=0)
{
printf("tid2 创建失败\n");
return -1;
}
pthread_join(tid1,NULL);//回收
pthread_join(tid2,NULL);
return 0;
}
思维导图