#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFER_SIZE 1024
int main(int argc,char *argv[])
{
int from_fd,to_fd;
int read_bytes,write_bytes;
char buffer[BUFFER_SIZE];
char *ptr;
/*检测输入的参数是否包含源文件和目标文件*/
if( argc != 3 )
{
printf("Usage:%s fromfile tofile\n\a",argv[0]);
exit(1);
}
/*源文件不能和目标文件相同*/
if( strcmp(argv[1],argv[2]) == 0 )
{
printf("Fromfile and tofile are the same!\n\a");
exit(1);
}
/*源文件以只读打开,若打开失败,程序结束*/
if( (from_fd=open(argv[1],O_RDONLY)) == -1 )
{
printf("Fromfile open failed!\n\a");
exit(1);
}
/*目标文件以只写打开,并且若不存在则新建,打开失败则程序结束*/
if( (to_fd=open(argv[2],O_CREAT | O_TRUNC | O_WRONLY)) == -1 )
{
printf("Tofile open failed!\n\a");
exit(1);
}
/*仅当读到的字节数不等于0的时候,进行接下来的拷贝工作*/
while( (read_bytes=read(from_fd,buffer,BUFFER_SIZE)) )
{
if(read_bytes == -1)
{
printf("Fromfile read error!\n\a");
exit(1);
}
else if(read_bytes > 0)
{
ptr = buffer;
while( (write_bytes=write(to_fd,ptr,read_bytes)) )
{
/*写入失败,程序结束*/
if(write_bytes == -1)
{
printf("Tofile write error!\n\a");
exit(1);
}
/*一次读出的数据全部写入,退出本次写操作,进行下一次读操作*/
else if(write_bytes == read_bytes)
break;
/*在写入时可能发生意外,此时要继续写入*/
else if(write_bytes > 0)
{
ptr += write_bytes;
read_bytes -= write_bytes;
}
}
}
}
close(from_fd);
close(to_fd);
return 0;
}
经典的文件拷贝函数及算法
最新推荐文章于 2021-06-13 15:57:08 发布