#include<myhead.h>
typedef struct Inoe
{
char *argc1;
char *argc2;
int len;
int fd1;
int fd2;
}*p;
//拷贝文件函数
void copy(/*const char *srcfile,const char *desfile,*/int len,int fd1,int fd2){
char str1[128]="";
int res,sum=0;
while(1){
res=read(fd1,str1,sizeof(str1));
sum+=res;
if(sum>=len||res==0){
write(fd2,str1,res-(sum-len));
break;
}
write(fd2,str1,res);
}
}
//分支线程
void *task(void *arg){
sleep(1);
p buf=(p)arg;
copy(/*buf->argc1,buf->argc2,buf->len,*/buf->fd1,buf->fd2);
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
/*
//判断终端输入字符串是否符合要求
if(argc!=3){
perror("enter error");
return -1;
}
*/
int fd1=-1;
if( fd1=open("./text.txt",O_RDWR|O_CREAT|O_TRUNC,0664)==-1 )
{
perror("open error");
return -1;
}
printf("fd1=%d\n",fd1);
int fd2=-1;
if( fd2=open("./copy_text.txt",O_RDWR|O_CREAT|O_TRUNC,0664)==-1 )
{
perror("open error");
return -1;
}
char str[128]="";
printf("please enter str:\n");
int a;
while(1){
a=read(0,str,sizeof(str));
write(fd1,str,a);
//printf("%d\n",a);
if( a<sizeof(str) ){
break;
}
}
lseek(fd1,0,SEEK_SET);
int len=lseek(fd1,0,SEEK_END);
pthread_t tid=-1;
struct Inoe buf={/*"./text.tex","./copy_text.txt",*/len-len/2,fd1,fd2};
if( pthread_create(&tid,NULL,task,&buf)!=0 )
{
printf("create error\n");
return -1;
}
lseek(fd1,0,SEEK_SET);
//主线程拷贝前半个文件
copy(/*argv[1],argv[2],*/len/2,fd1,fd2);
pthread_t tid1=pthread_self();
pthread_join(tid,NULL);
pthread_join(tid1,NULL);
close(fd1);
close(fd2);
return 0;
}
2024.2.21
于 2024-02-21 23:52:19 首次发布