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

Luc*_*cas -1 c++ fstream file visual-studio

我试图通过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;
}
Run Code Online (Sandbox Code Playgroud)

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

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

谢谢=)

Pet*_*esh 6

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

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

编辑正如已经指出的那样,这是不好的做法,导致读取最后一行两次或一个迷失空的最后一行.更正确的循环写法将是:

string output;
while (getline(myReadFile, output)) {
  cout<<output<<"\n";
}
Run Code Online (Sandbox Code Playgroud)

**编辑 - 在这里留下坏的,邪恶的代码:

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

string output;
while (myReadFile.good()) {
  getline(myReadFile, output);
  cout<<output<<"\n";
}
Run Code Online (Sandbox Code Playgroud)