将缓冲的文本数据读取到字符串

时间:2011-03-30 10:52:45

标签: c++ string file stl

您好我想从一个挂起的文本文件数据直接读取到字符串 我知道我可以使用以下内容:

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

但这样就可以一步完成整个文件的读取。 我想在几个步骤中阅读它,因为这是非常大约50GB的文件。 我怎么能这样做? 谢谢你的建议Herzl。

2 个答案:

答案 0 :(得分: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 :(得分:0)

我会选择好的老fopen和fread,他们会在这种情况下给你更多的控制权。