#include<head.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[10] = {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){
fprintf(stderr,"input error,try again\n");
fprintf(stderr,"usage:./a.out srcfile destfile\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]))
{
perror("thread 1 create error");
return -1;
}
if (pthread_create(&tid2, NULL, task, (void *)&f[1]))
{
perror("thread 2 create error");
return -1;
}
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
return 0;
return 0;
}