文件IO拷贝应用
创建子父进程,子进程将1.txt内容拷贝在2.txt中,父进程将3.txt内容拷贝在4.txt中。
#include<myhead.h>
int main(int argc, const char *argv[])
{int fd1,fd2,fd3,fd4;fd2=open("./2.txt",O_WRONLY|O_CREAT|O_TRUNC,0664);if(fd2==-1){perror("open fd2");return -1;}fd1=open("./1.txt",O_RDONLY);if(fd1==-1){perror("open fd1");return -1;}fd4=open("./4.txt",O_WRONLY|O_CREAT|O_TRUNC,0664);if(fd4==-1){perror("open fd4");return -1;}fd3=open("./3.txt",O_RDONLY);if(fd3==-1){perror("open fd3");return -1;}pid_t pid;pid =fork();char buff[100];char s[100];while(1){if(pid>0){int len=read(fd3,buff,sizeof(buff));if(len==0){break;}write(fd4,buff,len);printf("父进程拷贝成功\n");}else if(pid==0){int p=read(fd1,s,sizeof(s));if(p==0){break;}write(fd2,s,p);printf("子进程拷贝成功\n");}else {perror("创建失败,fork");}}close(fd1);close(fd2);close(fd3);close(fd4);while(1);return 0;
}
代码演示