2012-12-27 102 views
2

我的功能是copy2,我在cplusplus.com上找到了功能copy1,我用的是copy2並且有問題,但是拷貝1沒問題,copy2導致關於測試文件mp3的atist,title,...的損失信息,我不明白爲什麼?爲什麼ofstream :: get()和put()會導致信息丟失?

#include <fstream> 
#include <iostream> 
using namespace std; 

void copy1() 
{ 
    char * buffer; 
    long size; 

    ifstream infile ("Test.mp3",ifstream::binary); 
    ofstream outfile ("Test2.mp3",ofstream::binary); 

    // get size of file 
    infile.seekg(0,ifstream::end); 
    size=infile.tellg(); 
    infile.seekg(0); 

    // allocate memory for file content 
    buffer = new char [size]; 

    // read content of infile 
    infile.read (buffer,size); 

    // write to outfile 
    outfile.write (buffer,size); 

    // release dynamically-allocated memory 
    delete[] buffer; 
    cout<<"xong"; 
    outfile.close(); 
    infile.close(); 
    return ; 
} 
void copy2(){ 
    ifstream infile ("Test.mp3",ios::binary); 
    ofstream outfile ("Test1.mp3",ios::binary); 
    char c; 
    while(!infile.eof()) 
    { 
    infile.get(c); 
    outfile.put(c); 
    } 
} 
int main() { 
    copy2(); 
} 
+0

你怎麼知道信息丟失了?你用什麼程序/工具/過程來確定? –

回答

0

while(!infile.eof())會引起麻煩,因爲它可以返回在一定條件下錯誤的結果。 我有類似的問題。嘗試使用像這樣的東西:

while (getline(infile,data))           
    {           
      cout<<data<<endl; 
    } 
+0

爲什麼複雜呢? http://coliru.stacked-crooked.com/a/7bc6ba68e7212b3a –

相關問題