思维导图
文件的拷贝
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<errno.h>
#include<pthread.h>
//定义线程处理函数
//线程1拷贝前半部分
void *task1(void *arg)
{
printf("这是子线程1\n");
int fd1,fd2;//定义文件读写标识符
if((fd1=open("./1.txt",O_RDONLY))==-1)
{
perror("open 1.txt");
}
if((fd2=open("./5.txt",O_RDWR|O_CREAT|O_APPEND,0664))==-1)
{
perror("open 5.txt");
}
//求文件长度
int len=lseek(fd1,0,SEEK_END);
// printf("len=%d\n",len);
//定位光标
lseek(fd1,0,SEEK_SET);
lseek(fd2,0,SEEK_SET);
int len_half=len/2;
//开始拷贝
int buf1[10];
int ret=0;
int count =0;//累加拷贝的字数
while( ret = read(fd1,buf1,sizeof(buf1)) )
{
count +=ret;
if(count>len_half)
{
write(fd2,buf1,ret-(count-len_half));
break;
}
write(fd2,buf1,ret);
}
printf("前半部分拷贝完成\n");
pthread_exit(NULL);
}
//线程2拷贝后半部分
void *task2(void *arg)
{
sleep(1);
printf("这是子线程2\n");
int fd5,fd6;//定义文件读写标识符
if((fd5=open("./1.txt",O_RDONLY))==-1)
{
perror("open 1.txt");
}
if((fd6=open("./5.txt",O_RDWR|O_CREAT|O_APPEND,0664))==-1)
{
perror("open 5.txt");
}
//求文件长度
int len=lseek(fd5,0,SEEK_END);
// printf("len=%d\n",len);
int len_half=len-len/2;
//定位光标
lseek(fd5,len_half,SEEK_SET);
lseek(fd6,len_half,SEEK_SET);
//开始拷贝
int buf2[10];
int ret2=0;
int count2 =0;//累加拷贝的字数
while(ret2=read(fd5,buf2,sizeof(buf2)))
{
count2 +=ret2;
if(count2>len_half)
{
write(fd6,buf2,ret2-(count2-len_half));
break;
}
write(fd6,buf2,ret2);
}
printf("后半部分拷贝完成\n");
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
pthread_t tid1,tid2;//线程号
if(pthread_create(&tid1,NULL,task1,NULL))
{
perror("create pthraed");
return -1;
}
if(pthread_create(&tid2,NULL,task2,NULL))
{
perror("create pthraed");
return -1;
}
printf("这是主线程\n");
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
return 0;
}
ubu
运行结果