#include<myhead.h>
int len;
typedef struct
{
const char *srcfile;
const char *destfile;
}info;
//定义一个拷贝函数
int copy_file(const char *srcfile,const char *destfile,int len,int start)
{
//打开源文件
int srcfd=-1;
int destfd=-1;
if((srcfd=open(srcfile,O_RDONLY))==-1)
{
printf("open error");
return -1;
}
//打开目标文件
if((destfd=open(destfile,O_RDWR|O_CREAT|O_TRUNC,0664))==-1)
{
printf("open error");
return -1;
}
lseek(srcfd,start,SEEK_END);
lseek(destfd,start,SEEK_END);
char buf[128];
int sum=0;
while(1)
{
int res=read(srcfd,buf,sizeof(buf));
sum+=res;
if(sum>=len || res==0)
{
write(destfd,buf,res-(sum-len));
break;
}
write(destfd,buf,res);
}
//关闭文件
close(srcfd);
close(destfd);
return 0;
}
//定义第一个分支线线程
void *task1(void *arg)
{
info buf=*((info *)arg);
int srcfd=-1;
int destfd=-1;
//以只读的形式打开源文件
if((srcfd=open(buf.srcfile,O_RDONLY))==-1)
{
printf("open srcfile error");
return 0;
}
//以只写的形式打开目标文件
if((destfd=open(buf.destfile,O_WRONLY))==-1)
{
printf("open destfile error");
return 0;
}
copy_file(srcfd,destfd,0,len/2);
//关闭文件
close(srcfd);
close(destfd);
//退出线程
pthread_exit(NULL);
}
//定义第二个分支线程
void *task2(void *arg)
{
info buf=*((info *)arg);
int srcfd=-1;
int destfd=-1;
//以只读的形式打开源文件
if((srcfd=open(buf.srcfile,O_RDONLY))==-1)
{
printf("open srcfile error");
return 0;
}
//以只写的形式打开目标文件
if((destfd=open(buf.destfile,O_WRONLY))==-1)
{
printf("open destfile error");
return 0;
}
//调用复制函数
copy_file(srcfd,destfd,len,len-(len/2));
//关闭文件
close(srcfd);
close(destfd);
//退出线程
pthread_exit(NULL);
}
/*
//定义获取长度的函数并创建目标文件
int get_file_len(const char *srcfile,const char *destfile)
{
//以只读的形式打开源文件
if((srcfd=open(srcfile,O_RDONLY))==-1)
{
printf("open srcfile error");
return -1;
}
if((destfd=open(srcfile,O_WRONLY|O_CREAT|O_TRUNC,0664))==-1)
{
printf("open destfile error");
return -1;
}
int l=lseek(srcfd,0,SEEK_END);
close(srcfd);
close(destfd);
return l;
}
*/
int main(int argc, const char *argv[])
{
pthread_t tid;
//pthread_t tid2;
//判断外部传参
if(argc!=3)
{
printf("input error");
return -1;
}
//获取文件长度
int srcfd=-1;
if((srcfd=open(argv[1],O_RDONLY))==-1)
{
perror("open error");
return -1;
}
len=lseek(srcfd,0,SEEK_END);
close(srcfd);
//构建目标文件
int destfd=-1;
if((destfd=open(argv[2],O_CREAT|O_RDWR|O_TRUNC,0664))==-1)
{
perror("open error");
return -1;
}
close(srcfd);
//定义结构体
info s={argv[1],argv[2]};
//创建两个线程
if(pthread_create(&tid,NULL,task1,&s))
{
printf("tid create error");
return -1;
}
sleep(1);
if(pthread_create(&tid,NULL,task2,&s))
{
printf("tid create error");
return -1;
}
sleep(1);
//回收资源
pthread_join(tid,NULL);
return 0;
}