2012-05-03 181 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,使用需要一個尺寸參數的構造函數,所以你可以指定字符串的初始大小。