2012-05-03 182 views
-1

我想通过C++读取一个巨大的txt。它有70MB。我的目标是逐行字符串并生成另一个更小的txt,仅包含我需要的信息。从C++读取巨大的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) 未处理的异常:0000005:访问冲突读取位置0x3a70fcbc。

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

感谢=)

+0

立即死亡吗?中途加工?在处理文件结束时? –

+0

您的输入循环测试EOF的方式是[坏习惯](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong)。 – Blastfurnace

回答

6

你的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"; 
} 
+0

谢谢,完美的工作=) – Lucas

+0

你在这段代码中测试EOF的方式是[坏习惯](http://stackoverflow.com/questions/4324441/testing-stream-good-or-stream-eof-reads -last线-两次)。 – Blastfurnace

2

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

0

您未使用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,使用需要一个尺寸参数的构造函数,所以你可以指定字符串的初始大小。