2015-08-28 68 views
2
char* readFromFile(char* location) 
{ 
    int total = 0; 
    ifstream ifile = ifstream(location); 
    ifile.seekg(0, ifile.end); 
    total = ifile.tellg(); 

    cout << "Total count" << total << endl; 
    char* file = new char[total+1]; 

    ifile.seekg(0, ifile.beg); 

    ifile.read(file, total+1); 

    cout <<"File output" << endl<< file << "Output end"<<endl; 

    return file; 
} 

這裏是打印文件數據,但它也附加了一些垃圾數值。我應該如何解決它?C++ ifstream在從文本文件中讀取數據時追加垃圾數據

+1

Null終止你的字符串? –

回答

5

read只是讀取了一定數量的字節,它並沒有終止該序列。雖然cout期望一個空終止的序列,因此它會繼續打印位於數組之後的隨機內存,直到它運行到0.因此,您需要分配一個額外的字符,然後用空字符填充它。

char* readFromFile(char* location) 
{ 
    int total = 0; 
    ifstream ifile = ifstream(location); 
    ifile.seekg(0, ifile.end); 
    total = ifile.tellg(); 

    cout << "Total count" << total << endl; 
    char* file = new char[total+1]; 

    ifile.seekg(0, ifile.beg); 

    ifile.read(file, total); //don't need the +1 here 

    file[total] = '\0'; //Add this 

    cout <<"File output" << endl<< file << "Output end"<<endl; 

    return file; 
} 
+0

它仍然通過-51 ascii值填充字符串。你能說出什麼是錯的嗎? – varuog

+0

@fallenAngel,我會先用十六進制編輯器檢查你的文件。確保數據是正確的。然後如果這是正確的,請仔細檢查所有變量以及它們的用法。之後,我會設置一個斷點並逐步完成代碼,並仔細檢查您是否在每一步都做了正確的事情。 –

+0

我已經在十六進制編輯器中進行了檢查,顯示正常。 (更新)如果我傳遞二進制標誌,它工作正常。 – varuog