系统语言文件操作实现两个文档内容的复制

代码

/*****************************************************
copyright (C), 2014-2015, Lighting Studio. Co.,     Ltd. 
File name:
Author:Jerey_Jobs    Version:0.1    Date: 
Description:
Funcion List: 
*****************************************************/

#include <stdio.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<string.h>
#include<stdlib.h>
#include<errno.h>

#define BUFFER_SIZE 1024 //缓存区大小
int main(int argc,char ** argv) 
{
	int from_fd; //原始文件
	int to_fd; //目标文件
	int bytes_read,bytes_write;//实际读写字节数
	char buffer[BUFFER_SIZE];//缓冲区
	char *ptr;//数组名不可以改,所以用指针;本身读取所字节型所以用CHAR

	 if(argc != 3) //0可执行文件文件名(./),1源文件文件名,2是目标文件名
      {
		  printf("usage:from file and to file !\n");
		  exit(-1);
	  }

	  //源文件和目标文件已经输入执行下面程序

	 from_fd = open(argv[1],O_RDONLY);

	  if(from_fd == -1)   //源文件打开判断
	  {
		  perror("open from file fail");//错误处理标志
		  exit(-1);
	  }
	 
	  to_fd = open(argv[2],O_WRONLY | O_CREAT,S_IWUSR | S_IRUSR);//没有则自动创建
	  if(to_fd == -1)   //目标文件打开判断
	  {
		  perror("open to file fail");//错误处理标志
		  exit(-1);
	  }

	  while(bytes_read = read(from_fd,buffer,BUFFER_SIZE))//不能保证一次就把文件复制完所以需多次循环
		 // ,read遇到结束标志的时候为0,表示已经读完;
	  {
		  if(bytes_read == -1 && errno != EINTR)//其他原因引起的中断
           {
			   perror("error break!\n");
			   break;//退出读的操作
		   }
		  else if(bytes_read > 0)
		  {
			  ptr = buffer;
			  //解决部分写的问题
			  while(bytes_write = write(to_fd,ptr,bytes_read))//ptr执行缓存区写的地址,读多少写多少
		      {
				  if(bytes_write == -1 && (errno != EINTR))
				  {
					  perror("write break!\n");
					  break;//退出写的操作
				  }
				  else if(bytes_write == bytes_read)//写入完毕
				  {
					  break;
				  }
				  else if(bytes_write > 0)
				  {
					  ptr += bytes_write;//往后移动
					  bytes_read = bytes_write;
				  }
			  }

			  if(bytes_write == -1)
			  {
				  break;//退出while循环
			  }
		  }
	  }
		  
	  close(from_fd);
	  close(to_fd);
		  return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值