0

I'm trying to read a text file that contains only strings. It is compiling and opening but when reading it just displays junk that has no bearing to the characters in the file at all.

Can anyone see what's wrong?

#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; } 

end edited to:

input = new char[size]; myfile.seekg(0, fstream::beg); while(!myfile.eof()) { myfile.read(input,size); } cout<<input; system("pause"); 
1
  • input = new char[size]; No delete[]. That's a memory leak. Use a standard library container instead. Commented Dec 10, 2012 at 21:36

1 Answer 1

2

You seek to the end of the file before trying to read:

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

To make this work, you'll have to seek to the beginning first.

Also note that myfile.read() will not append a NUL terminator.

Sign up to request clarification or add additional context in comments.

3 Comments

Its reading the text but there is still a lot of junk coming afterwards. I've tried including a while !eof loop but that didn't work. I'll show the edited code above.
@MatthewParker: There's no NUL terminator. You have to add it yourself (making sure you've allocated space for it). Alternatively, put the text into a std::string.
As in I have to add the NUL terminator to the text file "0". If I save this as a binary will this happen automatically?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.