在c++中读取大的txt文件

Read large txt file in c++

本文关键字:txt 文件 读取 c++      更新时间:2023-10-16

我想读取一个内存约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
.....

我如何在c++中有效地做到这一点?

逐行读取文件:

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.

不显式调用close的原因参见:
544年https://codereview.stackexchange.com/questions/540/my-c-code-involving-an-fstream-failed-review/544

如果效率是你的主要目标(可能不是)。然后将整个文件读入内存并从那里进行解析:参见下面的Thomas:用c++

读取大型文本文件

将整个文件读入内存,然后在内存中处理内容。

文件资源(例如硬盘驱动器)在电机保持旋转时效率最高。所以一次大的数据读取比5次小的数据读取更有效率。

在大多数平台上,访问内存比访问文件要快。利用这些信息,可以通过将数据读入内存然后处理内存来提高程序的效率。

结合这两种技术将产生更高的性能:在一个事务中,将尽可能多的数据读入内存,然后处理内存。

有些人声明charunsigned char的大数组(用于二进制数据)。其他人告诉std::string或std::vector保留大量内存,然后将数据读入数据结构。

同样,块读取(a.k.a。istream::read())将绕过大多数c++流设施的慢部分。

使用文件流:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
    string line;
    ifstream myfile ("example.txt");
    if (myfile.is_open())
    {
        while ( getline(myfile, line) )
            cout << line << endl;
        myfile.close();
    }
    else 
    {
        cout << "Unable to open file"; 
    }
    return 0;
}

5MB确实不是一个大文件。流会一次帮你读取数据块,但实际上;几乎所有运行这个程序的机器都可以直接读取5MB的内存,没有问题。