2014-01-10 44 views
3

複製文件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 

任何人都知道問題在哪裏?

+1

我看不到你在哪裏創建這個輸出。 _PRODUCE A TESTCASE_(今晚第六次) –

回答

5

你應該做

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

你正經過bs,這是fread被允許讀取的最高金額。 brfread實際上讀取的金額。

+1

我的不好,謝謝:) – fwriteErr

7

忽略計數值(BR)

其實你寫bs

一個不好的變量命名的危險的好例子!