1、用多线程进行文件拷贝
#include<myhead.h>//参数结构体创建
typedef struct INFO
{const char *srcfile;const char *destfile;int length;
}Info;//定义获取文件长度的函数
int get_file_len(const char *srcfile,const char *destfile){int srcfd,destfd;//只读形式打开源文件 if((srcfd=open(srcfile,O_RDONLY))==-1){perror("open error");return -1;}//打开目标文件,不存在创建if((destfd=open(destfile,O_WRONLY|O_CREAT|O_TRUNC,0664))==-1){perror("open error");return -1;}int len =lseek(srcfd,0,SEEK_END);close(srcfd);close(destfd);return len;
}//定义文件拷贝函数
int copy_file(const char *srcfile,const char *destfile,int start,int len){int srcfd,destfd;if((srcfd=open(srcfile,O_RDONLY))==-1){perror("open error");return -1;}if((destfd=open(destfile,O_WRONLY))==-1){perror("open error");return -1;}//移动文件的光标lseek(srcfd,start,SEEK_SET);lseek(destfd,start,SEEK_SET);int sum=0;//完成拷贝工作char buf[128]="";while(1){int res = read(srcfd,buf,sizeof(buf));sum +=res;if(sum>=len||res==0){write(destfd,buf,sizeof(buf));break;}write(destfd,buf,sizeof(buf));}//关闭文件close(srcfd);close(destfd);return sum;
}//分支线程
void *task(void *arg){Info buf = *(Info *)arg;copy_file(buf.srcfile,buf.destfile,buf.length/2,buf.length-buf.length/2);//线程退出pthread_exit(NULL);
}//主线程
int main(int argc, char const *argv[])
{//判断外部传参if(argc!=3){printf("input file error\n");printf("usage: ./a.out srcfile destfile");return -1;}//获取源文件长度int len=get_file_len(argv[1],argv[2]);//参数结构体赋值Info buf={argv[1],argv[2],len};//创建多线程pthread_t tid = 1;if(pthread_create(&tid,NULL,task,&buf)!=0){printf("pthread_create error\n");return -1;}copy_file(argv[1],argv[2],0,len/2);if(pthread_join(tid,NULL)==0)printf("拷贝成功\n");return 0;
}