#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include<stdlib.h>
#include <errno.h>
#include<string.h>
#define MAXSIZE 1024
int main(int agrc ,char * agrv[ ])
{
int from_fd,to_fd;
int bytes_read,byte_write;
if(3 != agrc)
{
fprintf(stderr,"%s 用法: 源文件 目标文件",agrv[0]); // 如果使用方式不对,提示用法
exit(1);
}
if((from_fd=open(argv[1],O_RDONLY)) == - 1)
{
fprintf(stderr,"打开 %s Error:%s",agrv[1],strerror(errno)); //打开源文件,打开失败,报错误原因
exit(1);
}
if((to_fd =open(agrv[2],O_WRONLY|O_CREAT,S_IRUSR|S_IWUSR)== -1 )
{
fprintf(stderr,"打开 %s Error:%s ,agrv[2],strerror(errno)); //打开目标文件,失败报错
exit(1);
}
while(bytes_read= read(from_fd,buffer,MAXSIZE)) //读取源文件的内容
{
if(bytes_read==-1 && (errrno!= EINTR )) //一个致命的错误发生了
break;
if(bytes_read>0) //读到了数据
{
ptr=buffer; //buffer的首地址赋给ptr
while(bytes_write= write(to_fd,ptr,bytes_read) //开始写数据
{
if(bytes_write==-1 && (errno != (EINTR))
{
break;
}
else if(byte_write== bytes_read) //一次写完,就结束
break;
else if (bytes_write>0) //写的数据大于0,但一次读不完
{
ptr+=bytes_write; //读的位置相应往后移
bytes_read-=bytes_write; //剩下的数据大小
}
}
if(bytes_write== -1) //写数据失败
break;
}
}
while(1);
close(from_fd); //open 配 close使用
close(to_fd);
exit(0);
}