C语言实现文件拷贝

/**********************************************************************
* 函数名称:FileCopy
* 功能描述:文件拷贝
* 输入参数:srcFile
*				   dstFile -
* 输出参数:无
* 返 回 值:	状态码
* 其它说明:
***********************************************************************/
E_StateCode FileCopy(const char *srcFile, const char *dstFile)
{
	#define BUFFER_SIZE 1024
	int		from_fd,to_fd;
	int		bytes_read,bytes_write;
	char		buffer[BUFFER_SIZE];
	char		*ptr;

	int	eCode = -1;

	if ((NULL == srcFile) || (NULL == dstFile))
	{
		return eCode ;
	}
	/* 打开源文件 */

	if((from_fd = open(srcFile,O_RDONLY)) == -1)
	{
		dbprintf("Open %s Error:%s\n", srcFile, strerror(errno));
		return eCode ;
	}

	/* 创建目的文件 */

	if((to_fd = open(dstFile,O_WRONLY|O_CREAT,S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) == -1)
	{
		dbprintf("Open %s Error:%s\n", dstFile, strerror(errno));
		close(from_fd);
		return eCode ;
	}

	/* 以下代码是一个经典的拷贝文件的代码 */
	while(0 != (bytes_read = read(from_fd,buffer,BUFFER_SIZE)))
	{
		/* 一个致命的错误发生了 */
		if((bytes_read == -1) && (errno != EINTR))
		{
			break;
		}
		else if(bytes_read > 0)
		{
			ptr = buffer;
			while(0 != (bytes_write=write(to_fd,ptr,bytes_read)))
			{
				if((bytes_write == -1) && (errno != EINTR))
				{
					/* 一个致命错误发生了 */
					break;
				}
				else if (bytes_write == bytes_read)
				{
					/* 写完了所有读的字节 */
					break;
				}
				else if(bytes_write > 0)
				{
					/* 只写了一部分,继续写 */
					ptr += bytes_write;
					bytes_read -= bytes_write;
				}
			}

			/* 写的时候发生的致命错误 */
			if(bytes_write == -1)
			{
				eCode = eCode ;
				break;
			}

		}
	}

	close(from_fd);
	close(to_fd);
    eCode = 0;
	return eCode;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值