C++ 分块读取文件后写入

291次阅读
没有评论

共计 813 个字符,预计需要花费 3 分钟才能阅读完成。

一般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);
}

 

正文完
 
admin
版权声明:本站原创文章,由 admin 2022-04-11发表,共计813字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
评论(没有评论)
验证码