Chinaunix首页 | 论坛 | 博客
  • 博客访问: 459142
  • 博文数量: 68
  • 博客积分: 2606
  • 博客等级: 上尉
  • 技术积分: 1308
  • 用 户 组: 普通用户
  • 注册时间: 2010-12-13 23:01
文章分类
文章存档

2012年(6)

2011年(62)

分类: LINUX

2011-06-01 16:42:36

文件拷贝函数的两种实现:
1.
#include
#include
#include
#include
#define BUFFER_SIZE 1024
int main (int argc, char **argv)
{
 FILE *from_fd;
 FILE *to_fd;
 long file_len = 0;
 char buffer[BUFFER_SIZE];
 char *ptr;
 
 if(argc < 3)
 {
  printf("usage:%s fromfile tofile\n", argv[0]);
  
  exit(1);
 }
 
 if((from_fd = fopen(argv[1], "rb")) == NULL)
 {
  printf("open file %s error\n", argv[1]);
  exit(1);
 }
 
 if ((to_fd = fopen(argv[2],"wb")) == NULL)
 {
 
  printf("open file %s error\n", argv[2]);
  exit(1);
 }
 
 /*测得文件的大小:ftell函数获取文件偏移的当前值,fseek()不像lseek()会返回读写位置,因此必须使用ftell()来取得目前读写的位置。*/
 fseek(from_fd,0L,SEEK_END);
 file_len = ftell(from_fd);
 fseek(from_fd,0L,SEEK_SET);
 printf("from file size is=%d\n",file_len);
 
 while(!feof(from_fd))//feof函数判断是否已经到了文件尾部,到文件尾部函数返回非零
 {
  fread(buffer, BUFFER_SIZE, 1, from_fd);
  if(BUFFER_SIZE >= file_len)
  {
   fwrite(buffer, file_len, 1, to_fd);
  }
  else
  {
   fwrite(buffer, BUFFER_SIZE, 1, to_fd);
   file_len -= BUFFER_SIZE;   
  }
  /*bzero(buffer, BUFFER_SIZE);*/
  memset(buffer, 0, BUFFER_SIZE);
 }
 
 fclose(from_fd);
 fclose(to_fd);
 
 return 0;
}
 
2.
#include
#include
#define BUFSIZE 1024
int main (int argc, char *argv[])
{
 FILE * src, *dest;
 int read_bytes = 0, write_bytes = 0;
 char buf[BUFSIZE] = {0};
 char *ptr;
 
 if(argc < 3)
 {
  printf("please input two files for cp\n");
  
  exit(EXIT_FAILURE);
 }
 
 if((src = fopen(argv[1], "r+")) == 0)
 {
  printf("open file %s error\n", argv[1]);
  exit(EXIT_FAILURE);
 }
 else
 {
  printf("open file %s success\n", argv[1]);
 }
 if ((dest = fopen(argv[2],"w+")) == 0)
 {
 
  printf("open file %s error\n", argv[2]);
  exit(EXIT_FAILURE);
 }
 else
 {
  printf("open file %s success\n", argv[2]);
 }
/*此处参数的位置很重要,fread正常返回值为第三个参数,即BUFSIZE的大小*/
  
 while (read_bytes = fread(buf, 1, BUFSIZE, src))
 {
  printf("read_bytes:%d\n",read_bytes);
  if (read_bytes < 0)
  {
   printf("read file %s failed", argv[1]);
   
   exit(EXIT_FAILURE); 
  }
  
  ptr = buf;
  
/*此处参数的位置很重要,fwrite正常返回值为第三个参数,即read_bytes的大小*/
  while (write_bytes = fwrite(ptr, 1, read_bytes, dest))
  {
   printf("write_bytes:%d\n",write_bytes);
   if(write_bytes < 0)
   {
    perror("write file error");
    
    break;
   }   
   else if (read_bytes == write_bytes)
   {
    printf("4096 success");
    break; 
   }
   else if (write_bytes > 0)
   {
    ptr += write_bytes;
    read_bytes -= write_bytes;
   }
  }
 }
 
 /*printf("read_bytes:%d,%s\n",read_bytes, buf);*/
 fclose(src);
 fclose(dest);
 
 return 0;
}
阅读(3384) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~