2013-03-21 93 views
1

我嘗試用vC++與此代碼C++讀取整個文本文件

ifstream file (filePath, ios::in|ios::binary|ios::ate); 
    if (file.is_open()) 
    { 
     size = (long)file.tellg(); 
     char *contents = new char [size]; 
     file.seekg (0, ios::beg); 
     file.read (contents, size); 
     file.close(); 
     isInCharString("eat",contents); 

     delete [] contents; 
    } 

讀取整個文本文件,但它不是獲取所有整個文件,爲什麼和如何處理呢?

注:文件大小爲1.87 MB和39854線

+0

請參閱以下頁面:http://stackoverflow.com/questions/2602013/read-whole-ascii-file-into-c-stdstring – woosah 2013-03-21 12:35:45

+0

可能的重複[什麼是最好的方式將文件轉換爲std: :C++中的字符串?](http://stackoverflow.com/questions/116038/what-is-the-best-way-to-slurp-a-file-into-a-stdstring-in-c) – 2013-03-21 13:24:22

回答

0

謝謝大家,我發現錯誤,其中, 只是下面的代碼讀取整個文件, 問題是VS觀察器本身,它只是顯示一定量的數據而不是全文本文件。

0

你真的應該得到的閱讀文檔的習慣。 ifstream::read在案,以有時不讀所有字節,並

The number of characters successfully read and stored by this function 
    can be accessed by calling member gcount. 

所以你可能會尋找到file.gcount()file.rdstate()調試問題。此外,對於這樣大的讀取,使用(在某些顯式循環中)istream::readsome成員函數可能更相關。 (我建議通過例如64K字節的塊讀取)。

PS它可能是一些實現或系統特定的問題。

2

你缺少以下行

file.seekg (0, file.end); 

前:

size = file.tellg(); 
file.seekg (0, file.beg); 

如本例discribed:http://www.cplusplus.com/reference/istream/istream/read/

+0

Thanmks,但我補充一點,並沒有區別仍然是文本的一部分 – HokaHelal 2013-03-21 12:54:16

+1

你總是有相同的金額?用file.gcount()檢查 – 2013-03-21 13:04:47

2

另一種方式來做到這一點:

std::string s; 
{ 
    std::ifstream file ("example.bin", std::ios::binary); 
    if (file) { 
     std::ostringstream os; 
     os << file.rdbuf(); 
     s = os.str(); 
    } 
    else { 
     // error 
    } 
} 

或者,您可以使用C庫函數fopen,fseek,ftell,fread,fclose。在某些情況下,c-api的速度可能更快,但會犧牲更多的STL接口。