2012-12-10 165 views
0

我想讀取僅包含字符串的文本文件。它正在編譯和打開,但在閱讀時只顯示與文件中的字符無關的垃圾。閱讀fstream返回垃圾

任何人都可以看到有什麼問題嗎?

#include <iostream> 
#include <fstream> 

using namespace std; 

fstream myfile; 
char* input; 

void main(void) 
{ 
    myfile.open("H://fstream_test.txt", fstream::in); 
    if(myfile.fail()) 
    { 
     cout<<"error"; exit(0); 
    } 
    cout<<"file is open"; 

    int beginning = myfile.tellg(); 
    myfile.seekg(0, fstream::end); 
    int end = myfile.tellg(); 
    int size = end-beginning; 
    cout<<size; //returns 15 

    input = new char[size]; 
    myfile.read(input,size); 

    cout<<input; 
    //returns junk 

    //for(int i=0;i<size;i++) 
     //cout<<input[i]; 
    //returns the same; 
} 

末編輯爲:

input = new char[size]; 
    myfile.seekg(0, fstream::beg); 
    while(!myfile.eof()) 
    { 
     myfile.read(input,size); 
    } 

    cout<<input; 
    system("pause"); 
+0

input = new char [size];不刪除[]。這是內存泄漏。改爲使用標準庫容器。 –

回答

2

你想讀之前尋求到文件的末尾:

myfile.seekg(0, fstream::end); 

爲了使這項工作,你就必須尋求首先開始。請注意,myfile.read()不會附加NUL終止符。

+0

它閱讀的文字,但仍然有很多垃圾後來。我試過包括一段時間!eof循環,但沒有奏效。我將顯示上面編輯的代碼。 –

+0

@MthethePParker:沒有NUL終結者。你必須自己添加它(確保你已經爲它分配了空間)。或者,將文本放入'std :: string'中。 – NPE

+0

正如我必須將NUL終結符添加到文本文件「0」。如果我將它保存爲二進制文件,這會自動發生嗎? –