经典的文件拷贝函数及算法

#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值