繁体   English   中英

从C ++读取巨大的txt文件?

[英]Reading huge txt files from C++?

我正在尝试通过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#指出解决方案,那也是可以接受的!

谢谢=)

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

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

编辑正如有人指出,这是不好的做法,并导致阅读的最后一行两次或空空如也最后一行。 循环的更正确的写法是:

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

**编辑-在此处留下错误的代码:

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

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

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

您没有使用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 ,请使用带有size参数的构造函数,以便您可以指定字符串的初始大小。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM