- 论坛徽章:
- 0
|
#include
#include
#include
#include
#include
#include
#include
#define BUF_SIZE 1024
int main(int argc,char **argv)
{
int fromfd,tofd;
int bytes_read,bytes_write;
char buffer[BUF_SIZE];
char *ptr;
/*command run parameter test*/
if(argc!=3)
{
fprintf(stderr,"Usage:%s srcfile destfile\n",argv[0]);
return 0;
}
/*open source file*/
if((fromfd=open(argv[1],O_RDONLY))==-1)
{
fprintf(stderr,"Open source file failed:%s\n",strerror(errno));
return 0;
}
/*create dest file*/
if((tofd=open(argv[2],O_WRONLY|O_CREAT,S_IRUSR|S_IWUSR))==-1)
{
fprintf(stderr,"Create dest file failed:%s\n",strerror(errno));
close(fromfd);
return 0;
}
/*copy file code*/
while(bytes_read=read(fromfd,buffer,BUF_SIZE))
{
if(bytes_read==-1 && errno!=EINTR) break; /*an important mistake occured*/
else if(bytes_read>0)
{
ptr=buffer;
/*write to dest file*/
while(bytes_write=write(tofd,buffer,bytes_read))
{
if(bytes_write==-1 && errno!=EINTR) break;
else if(bytes_write==bytes_read) break;
else if(bytes_write>0)
{
ptr+=bytes_write; /*move the ptr pointer to new position*/
bytes_read-=bytes_write;
}
}
if(bytes_write==-1) break;
}
}
close(fromfd);
close(tofd);
return 0;
}
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u1/56374/showart_1715665.html |
|