C ++ fwrite()写的比预期多

时间:2014-01-10 01:46:22

标签: c fwrite

复制文件时遇到问题

代码:

    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写入整个缓冲区忽略计数值(br)

一些例子:

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

任何人都知道问题出在哪里?

2 个答案:

答案 0 :(得分:7)

  

忽略计数值(br)

其实你写过bs

糟糕的变量命名危险的一个很好的例子!

答案 1 :(得分:5)

你应该做

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

您正在传递bs,这是fread允许阅读的最大金额。 brfread实际读过的金额。