一般c++读取文件使用获取文件大小,然后逐个写入,我们可以采取分块读取写入的方法,可以加快大文件的拷贝速度,比如申请一个64M的内存,每次读取64M,然后写入,记录取余后的,最后写写入即可,下面代码示例:
注:文件大小不能超过int最大表示范围,如需要更改,请按需修改为long等类型即可
#include <windows.h> #include <stdio.h> int main(int argc, char *argv[]) { if(argc <1 ){ exit; } printf(argv[1]); char s[MAX_PATH],s2[MAX_PATH]; char *buf = (char *)malloc(64 * 1024 * 1024); strcpy(s, argv[1]); FILE *fd,*fs = fopen(s, "rb"); int c,l = strlen(s); strcpy(s2, s); for(int i=l;i>0;i--){ if(s2[i] == '\\'){ c = ++i; s2[i] = '\0'; break; } } strcat(s2, "copy_"); strcat(s2,&s[c]); fd = fopen(s2, "wb"); fseek(fs, 0, SEEK_END); int fsize = ftell(fs), count = fsize / (64 * 1024 * 1024 ), mod = fsize % (64 * 1024 * 1024); fseek(fs, 0, SEEK_SET); if(mod){ count++; } for(int i=0;i<count;i++){ if(mod&&i+1==count){ fread(buf, 1, mod, fs); fwrite(buf, 1, mod, fd); }else{ fread(buf, 1, 64 * 1024 * 1024, fs); fwrite(buf, 1, 64 * 1024 * 1024, fd); } } fclose(fs); fclose(fd); free(buf); }