#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>
#include <fcntl.h>
#define BUFFER_SIZE 1024
int main(int argc ,char *argv[])
{
int from_fd,to_fd;
char buffer[BUFFER_SIZE],*ptr;
int readchar,writechar;
if(argc!=3)
{
printf("Please input the right read file and write file\n");
exit(EXIT_FAILURE);
}
/*打开源文件*/
if((from_fd=open(argv[1],O_RDONLY))==-1)
{
printf("open file %s failure \n",argv[1]);
exit(EXIT_FAILURE);
}
/*打开目标文件*/
if((to_fd=open(argv[2],O_RDWR|O_CREAT,S_IRUSR|S_IWUSR))==-1)
{
printf("open file %s failure\n",argv[2]);
exit(EXIT_FAILURE);
}
/*复制文件*/
while(readchar=read(from_fd,buffer,BUFFER_SIZE))
{
/*读取发生致命错误*/
if((readchar==-1)&&(errno!=EINTR))
{
break;
}
ptr=buffer;
if(readchar>0)
{
while(writechar=write(to_fd,ptr,readchar))
{
/*写发生致命错误*/
if((writechar==-1)&&(errno!=EINTR))
{
break;
}
/*全部写入*/
else if(writechar==readchar)
{
break;
}
/*部分写入*/
else
{
ptr+=writechar;//将写入指针后移writechar个字节
readchar-=writechar;//将readchar减少writechar 说明已有writechar个字节写入
}
}
if(writechar==-1)
{
break;
}
}
}
close(from_fd);//关闭源文件
close(to_fd);//关闭目标文件
return 1;