用父子进程完成文件的拷贝
//转载
#include<myhead.h>
#include<sys/wait.h>
int main(int argc, const char *argv[])
{
int fd;
if((fd = open("./work.txt",O_RDONLY)) == -1)
{
perror("open file");
return -1;
}
int size;
size = lseek(fd,0,SEEK_END);
close(fd);
pid_t pid = fork();
if(pid < 0)
{
perror("fork error");
return -1;
}
else if(pid == 0)
{
int fd1,fd2;
if((fd1 = open("./work.txt",O_RDONLY)) == -1)
perror("open file");
if((fd2 = open("./work1.txt",O_WRONLY)) == -1)
perror("open file");
lseek(fd1,size/2,SEEK_SET);
char buf[4]="";
int ret,count=0;
while(1)
{
ret = read(fd1,buf,sizeof(buf));
count += ret;
if(count < size/2)
{
write(fd2,buf,ret);
}
else
break;
}
write(fd2,buf,ret-(count-size/2));
}
else
{
int fd1,fd2;
if((fd1 = open("./work.txt",O_RDONLY)) == -1)
perror("open file");
if((fd2 = open("./work2.txt",O_WRONLY)) == -1)
perror("open file");
lseek(fd1,0,SEEK_SET);
char buf[4]="";
int ret,count=0;
while(1)
{
ret = read(fd1,buf,sizeof(buf));
count += ret;
if(count < size/2)
{
write(fd2,buf,ret);
}
else
break;
}
write(fd2,buf,ret-(count-size/2));
}
return 0;
}
文件位置 IO/D6 名称copy.c