#include <myhead.h>
int get_len(const char *p1,const char *p2)
{
int fd1 = open(p1,O_RDONLY);
if(fd1==-1)
{
perror("open1");
return -1;
}
int fd2 = open(p2,O_WRONLY|O_CREAT|O_TRUNC,0664);
if(fd1==-1)
{
perror("open2");
return -1;
}
int len = lseek(fd1,0,SEEK_END);
close(fd1);
close(fd2);
return len;
}
int copy_file(const char *p1,const char *p2,int start,int len)
{
int fd1,fd2;
fd1 = open(p1,O_RDONLY);
if(fd1==-1)
{
perror("open1");
return -1;
}
fd2 = open(p2,O_WRONLY);
if(fd2==-1)
{
perror("open2");
return -1;
}
lseek(fd1,start,SEEK_SET);
lseek(fd2,start,SEEK_SET);
char buff[1024];
int sum=0;
while(1)
{
int res = read(fd1,buff,sizeof(buff));
sum+=res;
if(sum>=len||res==0)
{
write(fd2,buff,res-(sum-len));
break;
}
write(fd2,buff,res);
}
close(fd1);
close(fd2);
return 0;
}
void *fun1(void *arg)
{
int len = *(int*)arg;
copy_file("1.txt","2.txt",0,len/2);
pthread_exit(NULL);
}
void *fun2(void *arg)
{
int len = *(int*)arg;
copy_file("1.txt","2.txt",len/2,len-len/2);
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
if(argc!=3){
printf("外部传参错误\n");
return -1;
}
int len = get_len(argv[1],argv[2]);
pthread_t tid1,tid2;
pthread_create(&tid1,NULL,fun1,&len);
pthread_create(&tid2,NULL,fun2,&len);
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
pthread_exit(NULL);
return 0;
}