vim fopen.c 在终端创建一个fopen.c文件并打开

  1 #include <stdio.h>

  2 #include <stdlib.h>
  3 int main(int argc,char *argv[])  //main函数原型
  4 {
  5     if(argc < 3)
  6     {
  7         printf("too few argment\n");
  8     }
  9     char *dstfile = argv[2];
 10     char *srcfile = argv[1];
 11     FILE *srcFile = fopen(srcfile,"r+");//r+:Create an empty file and open it for update (both for input and output). If a file with the same name already exists its contents are discarded and the file is treated as a new empty file.创建一个空文件
 12     //创建源文件指针
 13     if(srcFile == NULL)  //判断源文件是否存在
 14     {
 15         printf("srcFile open failed!\n");
 16         exit(-1);  //异常退出   exit(0)表示正常退出
 17     }
 18     //创建目的文件指针
 19     FILE *dstFile = fopen(dstfile,"w+");//w+表示写方式: Open a file for update (both for input and output). The file must exist. 打开一个文件,并且该文件必须存在
 20     if(dstFile == NULL)
 21     {
 22         printf("dstFile open failed!\n");
 23         exit(-1);
 24     }
 25     char buffer[10000];
 26     //创建一个数组,用于接收字符串
 27     for(;;)
 28     {
 29         size_t readlen = 0;
 30         readlen = fread(buffer,1,sizeof(buffer),srcFile);
 31         //1代表从srcFile源文件按1字节1字节读
 32         if(readlen == 0)  //判断文件是否读到末尾
 33         {
 34                 break;
 35                 //退出循环
 36         }
 37         size_t writelen = 0;
 38         while(writelen < readlen)
 39         {
 40             writelen += fwrite(buffer + writelen,1,(readlen - writelen),dstFile);  //1字节1字节写入dstFile文件,buffer + writelen表示从上一次处接着写
 41         }
 42
 43     }
 44     fclose(srcFile);
 45     fclose(dstFile);  //最后要把文件关闭,不然会出现难以预料的错误
 46     return 0;
 47 }

 

 

在终端编译运行:gcc fopen.c表示编译该文件,然后会生成一个.o 文件。然后再运行,struct.c是已经存在的源文件,而struct.c.new是目的文件.

然后vim -O struct.c struct.c.new 在终端使用双页显示查看是否拷贝成功,你会发现文件里的内容按字节拷贝过去了。左边是源文件,右边是目的文件

posted on 2013-12-31 20:48  fooke  阅读(1933)  评论(0编辑  收藏  举报