2011-03-30 56 views
1

您好我想從掛起的文本文件中的數據直接讀取到一個字符串 我知道我可以使用以下命令:讀取緩衝文本數據串

ifstream infile("myfile"); 
string str(istreambuf_iterator<char>(infile), istreambuf_iterator<char>()); 

但這種方式在一個步驟中讀取整個文件。 我想在幾個步驟中閱讀它,因爲這是非常龐大的50GB文件。 我該怎麼做? 感謝您的建議Herzl。

+0

但是你想在一個字符串整個文件? – 2011-03-30 10:56:26

+0

不是整個文件一次。每次我想讀取1MB數據。處理它然後從文件讀取remiand數據。 – 2011-03-30 10:59:40

+1

[直接從std :: istream讀入std :: string]的可能的重複(http://stackoverflow.com/questions/1816319/reading-directly-from-an-stdistream-into-an-stdstring) – 2011-03-30 11:06:38

回答

1

我會做這樣的事情(由bufSize可以進行修改,以滿足您的需要):

#include <iostream> 
#include <string> 
#include <fstream> 

using namespace std; 

void ReadPartially(const char *file) 
{ 
    const unsigned bufSize = 10; 
    ifstream is(file); 
    string str(bufSize, '\0'); 
    unsigned count=0; 
    while(!is.eof()) 
    { 
     count++; 
     is.read(&str[0], bufSize); 
     cout << "Chunk " << count << ":[" << endl << str << "]" << endl; 
    } 
} 
+1

我並不認爲'&str [0]'會返回一個連續的內存塊(至少不是當前標準)...... – 2011-03-31 08:41:50

+0

你是對的。只有向量類保證了存儲數據的緩衝區的連續性。但在實踐中,我還沒有遇到任何與字符串類有關的問題。這是提到的好。 – INS 2011-04-14 20:53:32

0

我會帶着很好的老fopen和fread,他們給你更多的控制在這種情況下。

+0

性能如何? – 2011-03-30 12:05:58