文件数据块读取写入实现文件复制功能
size_t fread ( void *ptr, size_t size, size_t count, FILE *fp );
size_t fwrite ( void * ptr, size_t size, size_t count, FILE *fp );
用到的函数原型
#include <stdio.h> #include<stdlib.h> char* CopyFile(char* fileRead,char* fileWrite) { FILE* fpRead; FILE* fpWrite; int bufferLen=1024*4; char* buffer=(char*)malloc(bufferLen); int readCount; if((fpRead=fopen(fileRead,"rb"))==NULL||(fpWrite=fopen(fileWrite,"wb"))==NULL) { printf("error\n"); char ch=getchar(); return (char*)"error"; } while((readCount=fread(buffer,1,bufferLen,fpRead))>0) fwrite(buffer,1,readCount,fpWrite); free(buffer); fclose(fpRead); fclose(fpWrite); return nullptr; } int main(int argc,char* argv[]) { if(CopyFile(argv[1],argv[2])==nullptr) printf("copy file success\n"); else printf("copy file fail\n"); return 0; }
编译
sudo g++ copyFile.cc -o copyFile.exe
将copy_file1.txt内容拷贝到copy_file2.txt中
无情的摸鱼机器