【问题标题】:Reading huge txt files from C++?从 C++ 读取巨大的 txt 文件?
【发布时间】:2012-05-03 17:09:09
【问题描述】:

我正在尝试通过 C++ 阅读一个巨大的 txt。它有70mb。我的目标是逐行子串并生成另一个较小的 txt,其中仅包含我需要的信息。

我使用下面的代码来读取文件。它适用于较小的文件,但不适用于 70mb 的怪物。

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
  ifstream myReadFile;
  myReadFile.open("C:/Users/Lucas/Documents/apps/COTAHIST_A2010.txt");
  char output[100];
  if (myReadFile.is_open()) {
    while (myReadFile.eof()!=1) {
         myReadFile >> output;
         cout<<output;
         cout<<"\n";
     }


    }
  system("PAUSE");
  return 0;
}

这是我得到的错误: SeparadorDeAcoes.exe 中 0x50c819bc (msvcp100d.dll) 处未处理的异常:0xC0000005:访问冲突读取位置 0x3a70fcbc。

如果有人可以用 C 甚至 C# 指出解决方案,那也是可以接受的!

谢谢 =)

【问题讨论】:

  • 它会立即死亡吗?中途处理?在处理文件结束时?
  • EOF 的输入循环测试方式是bad practice

标签: c++ visual-studio file fstream


【解决方案1】:

您的char output[100] 缓冲区无法获取其中一行的内容。

理想情况下,您应该使用字符串目标,而不是 char[] 缓冲区。

编辑 正如已经指出的那样,这是一种不好的做法,会导致读取最后一行两次或最后一行出现空缺。更正确的循环写法是:

string output;
while (getline(myReadFile, output)) {
  cout<<output<<"\n";
}

**Edit - 在这里留下糟糕的、邪恶的代码:

您的内部 while 循环的快速重写可能是:

string output;
while (myReadFile.good()) {
  getline(myReadFile, output);
  cout<<output<<"\n";
}

【讨论】:

【解决方案2】:

我认为您的问题是您的一行超过 100 个字符。需要增加字符数组的大小。

【讨论】:

    【解决方案3】:

    您没有使用std::string,但包含了头文件。 决定。使用std::string 或字符数组。

    另外,使用std::istream::read 并将数组的大小提供给函数。您需要重复多次,因为 100 个字符远小于 70mb。

    尝试使用动态内存分配更大的数组:

    const unsigned int array_size = 1024 * 1024 * 1024;
    
    int main(void)
    {
      char * output;
    //...
      output = new char [array_size];
    // read into output
    // ...
    // clean up
      delete [] output;
      return EXIT_SUCCESS;
    }
    

    如果您使用std::string,请使用带有大小参数的构造函数,以便您可以指定字符串的初始大小。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-20
      • 1970-01-01
      • 2023-03-28
      • 2020-10-09
      • 2013-11-13
      • 2011-04-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多