在c++中读取大的txt文件
Read large txt file in c++
我想读取一个内存约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次小的数据读取更有效率。
在大多数平台上,访问内存比访问文件要快。利用这些信息,可以通过将数据读入内存然后处理内存来提高程序的效率。结合这两种技术将产生更高的性能:在一个事务中,将尽可能多的数据读入内存,然后处理内存。
有些人声明char
或unsigned 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的内存,没有问题。
相关文章:
- 如何将 txt 文件中的行分隔为组件C++
- 无法打开.txt文件
- 如何使用CLion在Mac上创建一个新的.txt文件
- 使用fstream对txt文件中的数字进行循环
- Visual Studio在尝试读取resource.txt文件时崩溃
- 如何从txt文件中读取多个不同长度的数组?
- 在一次迭代中从 txt 文件中读取多行
- 通过比较C++中的行在 txt 文件中搜索的最简单方法是什么?
- 写入超过 1GB 的.txt文件时出现奇怪的行为
- 视觉 如何循环访问C++中遵循类似格式的多个.txt文件?
- txt 文件中浮点数的最大和最小值
- 从.txt文件中读取浮点型数字并在公式中使用它们
- C++将文本从.txt文件解析为变量
- 在树结构.txt文件中搜索节点
- 为什么我无法打开/读取从 Python 调用的 C 扩展名中的 txt 文件?
- 在 txt 文件中显示前两个数字的程序
- 如何从具有两列的.txt文件创建并行数组?
- 如何使用c ++读取带有非英文字母的*.txt文件?(国际化)
- 如何像在 C++ 中处理数组一样对 .txt 文件中的字符进行寻址?
- 如何读取 TXT 文件并仅将 int 存储在 C 中