2012-12-10 56 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”。如果我将它保存为二进制文件,这会自动发生吗? –