#include <myhead.h>
typedef struct
{
const char* src;
const char* dest;
int start;
int len;
}info_t;
int get_src_file_len(const char* srcfile, const char* destfile)
{
int sfd,dfd;
int len = 0;
if((sfd=open(srcfile,O_RDONLY))==-1)
{
perror("open srcfile error");
return -1;
}
if((dfd=open(destfile,O_RDWR|O_CREAT|O_TRUNC,0664))==-1)
{
perror("open destfile error");
return -1;
}
len = lseek(sfd, 0, SEEK_END);
close(sfd);
close(dfd);
return len;
}
int copy_file(const char* srcfile, const char* destfile, int start, int len)
{
int sfd,dfd;
char buf[32]={0};
int ret=0,count=0;
if((sfd=open(srcfile,O_RDONLY))==-1)
{
perror("open srcfile error");
return -1;
}
if((dfd=open(destfile,O_RDWR))==-1)
{
perror("open destfile error");
return -1;
}
lseek(sfd,start,SEEK_SET);
lseek(dfd,start,SEEK_SET);
while(1)
{
ret = read(sfd,buf,sizeof(buf));
count+=ret;
if(ret ==0||count>len)
{
write(dfd, buf,ret-(count-len));
break;
}
write(dfd,buf,ret);
}
close(sfd);
close(dfd);
return 0;
}
void *task(void *arg)
{
info_t f=*(info_t *)arg;
copy_file(f.src, f.dest, f.start, f.len);
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
pthread_t tid1,tid2;
int len;
if(argc!=3)
{
printf("input file error\n");
printf("usage: ./a.out srcfile dstfile\n");
exit(EXIT_FAILURE);
}
len = get_src_file_len(argv[1],argv[2]);
info_t f[2] = {
{argv[1],argv[2],0,len/2},
{argv[1],argv[2],len/2,(len-len/2)},
};
if (pthread_create(&tid1,NULL,task,(void *)&f[0]))
return -1;
if (pthread_create(&tid2,NULL,task,(void *)&f[1]))
return -1;
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
return 0;
}