题目:实现一个文件的拷贝,先拷贝前半段,再拷贝后半段(1/2段)
调试: ./a.out fork.c info //拷贝fork.c 到info文件
运行效果:
源代码:
copy_file.c
#include<stdio.h>
#include<string.h>
#include<errno.h>
#include<stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int copy_file_fore(int fd_src,int fd_dest,int len);
int copy_file_last(int fd_src,int fd_dest,int len);
int init_open_file(int fd_src,int fd_dest,char const *path1, char const *path2);
int main(int argc, const char *argv[])
{
pid_t pit;
int fd_src,
fd_dest;
int len;
if(argc < 3)
{
fprintf(stderr,"Usage : %s,argv[1],argv[2]",argv[0]);
exit(EXIT_FAILURE);
}
if((fd_src = open(argv[1],O_RDONLY)) < 0)
{
fprintf(stderr,"FAIL TO OPRN FILE : %s,%s\n",argv[1],strerror(errno));
exit(EXIT_FAILURE);
}
if((fd_dest = open(argv[2],O_WRONLY | O_CREAT | O_TRUNC,0666)) < 0)
{
fprintf(stderr,"FAIL TO OPRN FILE : %s,%s\n",argv[2],strerror(errno));
exit(EXIT_FAILURE);
}
len = lseek(fd_src,0,SEEK_END);
ftruncate(fd_dest,len);
if((pit = fork()) == -1)
{
perror("FAIL TO CREAT PID:");
exit(EXIT_FAILURE);
}
if(pit != 0)
{
init_open_file( fd_src, fd_dest, argv[1], argv[2]);
copy_file_fore(fd_src,fd_dest , len / 2);
}
if(pit == 0)
{
init_open_file( fd_src, fd_dest, argv[1], argv[2]);
copy_file_last( fd_src, fd_dest , len / 2);
}
close(fd_src);
close(fd_dest);
return 0;
}
int copy_file_fore(int fd_src,int fd_dest,int len)
{
char buf[1024];
int n = 0;
int count = 0;
while(1)
{
n = read(fd_src,buf,sizeof(buf));
write(fd_dest,buf,n);
count += n;
if(count >= len)
break;
}
return 0;
}
int copy_file_last(int fd_src,int fd_dest,int len)
{
int n = 0;
char buf[1024];
lseek(fd_src,len,SEEK_SET);
lseek(fd_dest,len,SEEK_SET);
while(1)
{
n = read(fd_src,buf,sizeof(buf));
write(fd_dest,buf,n);
if(n <= 0)
break;
}
return 0;
}
int init_open_file(int fd_src,int fd_dest,char const *path1, char const *path2)
{
close(fd_src);
close(fd_dest);
if((fd_src = open(path1,O_RDONLY)) < 0)
{
fprintf(stderr,"FAIL TO OPRN FILE : %s,%s\n",path1,strerror(errno));
exit(EXIT_FAILURE);
}
if((fd_dest = open(path2,O_WRONLY )) < 0)
{
fprintf(stderr,"FAIL TO OPRN FILE : %s,%s\n",path2,strerror(errno));
exit(EXIT_FAILURE);
}
return 0;
}