C++ fwrite()写入的数据比预期多

3

我在复制文件时遇到了问题

代码:

    bool done;
    FILE* fin;
    FILE* fout;
    const int bs = 1024*64;//64 kb
    char* buffer[bs];
    int er, ew, br, bw;
    long long int size = 0;
    long long int sizew = 0;
    er = fopen_s(&fin,s.c_str(),"rb");
    ew = fopen_s(&fout,s2.c_str(),"wb");
    if(er == 0 && ew == 0){
        while(br = fread(buffer,1,bs,fin)){
            size += br;
            sizew += fwrite(buffer,1,bs,fout);
        }
        done = true;
    }else{
        done = false;
    }
    if(fin != NULL)fclose(fin);
    if(fout != NULL)fclose(fout);

一些方式可以使 fwrite 函数忽略 count 参数而写入整个缓冲区,下面是一些例子:

Copying 595 file of 635 DONE. 524288/524288 B
Copying 596 file of 635 DONE. 524288/524288 B
Copying 597 file of 635 DONE. 65536/145 B
Copying 598 file of 635 DONE. 65536/16384 B
Copying 599 file of 635 DONE. 65536/145 B
Copying 600 file of 635 DONE. 65536/67 B
Copying 601 file of 635 DONE. 65536/32768 B
Copying 602 file of 635 DONE. 65536/67 B

有人知道问题出在哪里吗?


1
我看不到你在哪里创建这个输出。_生成一个测试用例_(今晚已经是第六次了)。 - Lightness Races in Orbit
2个回答

7

忽略计数值 (br)

实际上你写的是 bs

这是变量命名不当的危害的一个好例子!


5

您应该做什么

        sizew += fwrite(buffer,1,br,fout);

您传递了参数“bs”,它是“fread”允许读取的最大数量。“br”是“fread”实际读取的数量。请保留HTML标记。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接