用c ++读取大型txt文件

Saf*_*ari 1 c++ format file

我想在内存中读取一个大约5MB的文件...文件有这种格式(它是一个文本文件)

ID 3:  0 itemId.1 0 itemId.2 0 itemId.5 1 itemId.7 ........................ 20 itemId.500
ID 50:  0 itemId.31 0 itemId.2 0 itemId.4 2 itemId.70 ........................ 20 itemId.2120
.....
Run Code Online (Sandbox Code Playgroud)

如何在c ++中有效地完成这项工作?

Mar*_*ork 5

逐行读取文件:

ifstream fin ("file.txt");
string     myStr;

while(getline(fin, myStr))   // Always put the read in the while condition.
{                            // Then you only enter the loop if there is data to
    //use myStr data         // processes. Otherwise you need to read and then
}                            //  test if the read was OK
                             //
                             // Note: The last line read will read up to (but not
                             //        past) then end of file. Thus When there is
                             //        no data left in the file its state is still
                             //        OK. It is not until you try and explicitly
                             //        read past the end of file that EOF flag is set.
Run Code Online (Sandbox Code Playgroud)

由于没有明确调用close的原因,请参阅:https:
//codereview.stackexchange.com/questions/540/my-c-code-involving-an-fstream-failed-review/544#544

如果效率是你的主要目标(可能不是).然后将整个文件读入内存并从那里解析:请参阅下面的Thomas:用c ++读取大型txt文件