#include
struct File{
char p1[20];
char p2[20];
};
/*
* function: 计算行号
* @param [ in] 读文件
* @param [out]
* @return 行号
*/
long line(const char*sourtext)
{
FILE *fp=NULL;
if((fp=fopen(sourtext,"r"))==NULL)
{
perror("fopen");
return -1;
}
fseek(fp,0,SEEK_END);
long line=0;
line=ftell(fp);
fclose(fp);
return line;
}
/*
* function: 拷贝文件
* @param [ in] 读文件,目标文件,写入位置,写的长度
* @param [out]
* @return 成功0,失败-1
*/
int my_copy(const char*sourtext,const char*desttext,int local,int len)
{
//读模式打开文件1
FILE *fp=NULL;
if((fp=fopen(sourtext,"r"))==NULL)
{
perror("fopen error");
return -1;
}
//写模式打开文件2
FILE *fp1=NULL;
if((fp1=fopen(desttext,"a"))==NULL)
{
perror("fopen error");
return -1;
}
//拷贝文件
fseek(fp,local,SEEK_SET);
fseek(fp1,local,SEEK_SET);
while(1)
{
char rbuf[128]="";
fread(rbuf,sizeof(rbuf),1,fp);
printf("%s",rbuf);
int temp=strlen(rbuf);
int sum=0;
sum=sum+temp;
if(strlen(rbuf)==0||sum>len)
{
fwrite(rbuf,1,temp-(sum-len),fp1);
break;
}
fwrite(rbuf,strlen(rbuf),1,fp1);
}
fclose(fp);
fclose(fp1);
}
void *task1(void *arg)
{
//线程1
struct File std=*(struct File*)arg;
int len=line(std.p1);
my_copy(std.p1,std.p2,0,len/2);
pthread_exit(NULL);
}
void *task2(void *arg)
{
//线程2
sleep(1);
struct File std=*(struct File*)arg;
int len=line(std.p1);
my_copy(std.p1,std.p2,len/2,len/2);
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
struct File std;
strcpy(std.p1,argv[1]);
strcpy(std.p2,argv[2]);
//创建俩个线程
pthread_t tid1=-1;
if(pthread_create(&tid1,NULL,task1,&std)!=0)
{
fprintf(stderr,"create error\n");
return -1;
}
pthread_t tid2=-1;
if(pthread_create(&tid2,NULL,task2,&std)!=0)
{
fprintf(stderr,"create error\n");
return -1;
}
//回收资源
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
return 0;
}
