标签:标准io 范围 fread set soft 方式 new 写入 代码
1 #include <stdio.h> 2 3 int main(int argc,char *argv) 4 { 5 //以只读的方式打开被复制的文件 6 FILE *srcFd = fopen("./source.txt","r"); 7 if(NULL == srcFd) 8 { 9 printf("open source file failed\n"); 10 return -1; 11 } 12 13 //以读写的方式创建一个不存在的文件 14 FILE *dstFd = fopen("./save.txt","w+"); 15 if(NULL == dstFd) 16 { 17 printf("open save file failed\n"); 18 return -1; 19 } 20 21 //进行获取文件大小的操作 22 fseek(srcFd,0,SEEK_END); //将光标移动到文件末尾 23 long fileSize = ftell(srcFd); //获取文件的大小 24 fseek(srcFd,0,SEEK_SET); //将光标恢复到文件的开头 25 26 //开辟一个新空间(动态开辟) 27 char *dataBuf = (char *)calloc(1,fileSize+1); 28 if(NULL == dataBuf) 29 { 30 printf("calloc a memory failed\n"); 31 return -1; 32 } 33 34 //读取文件的内容 35 long retSize = fread(dataBuf,1,fileSize,srcFd); 36 if(retSize != fileSize) 37 { 38 printf("read file context failed\n"); 39 return -1; 40 } 41 42 //写入保存文件中 43 retSize = fwrite(dataBuf,1,fileSize,dstFd); 44 if(retSize != fileSize) 45 { 46 printf("write context in file failed\n"); 47 return -1; 48 } 49 50 //关闭文件和释放内存空间 51 fclose(srcFd); 52 fclose(dstFd); 53 54 free(dataBuf); 55 56 return 0; 57 }
标签:标准io 范围 fread set soft 方式 new 写入 代码
原文地址:http://www.cnblogs.com/Older-Driver-of-Newer/p/6258992.html