-
ifstream junk output
I've been trying to use ifstream to read a file and output it to the console but I get garbage for ouput instead of the file itself.
This is the output that I get every time that I run the program:
Code:
p'+ 0+ n Platform=MCD PROCESSOR_ARCHITECTURE=x86 PROCESSOR_ARCHITEW6432=AMD64 PROCESSOR_IDENTIFIER=AMD64 Family 17 Model 3 Stepping 1, AuthenticAMD PROCESSOR_LEVEL=17 PROCESSOR_REVISION=0301 ProgramData=C:\ProgramData ProgramFiles=C:\Program Files (x86) Progra
Code:
#include <iostream>
#include <fstream>
using namespace std;
int main(){
int length;
char * buffer;
ifstream file;
file.open("books.txt", ios::binary);
if ( !file.is_open() ) {
cout<<"can't open.";
}
else{
file.seekg(0, ios::end);
length=file.tellg();
buffer=new char[length];
file.read(buffer,length);
file.close();
cout.write(buffer,length);
}
//cout<<"\n"<<length;
delete[] buffer;
cin.ignore();
cin.get();
return 0;
}
Does anyone know how I can fix this to output correctly?
-
You seek to the end of the file to get its length, but you forget to seek back to the beginning again in order to read it.
Had you bothered to check the error status after attempting to read, you would have seen that the read failed.
-
I wasn't aware that there was a function to check the error status until just now. Thanks for pointing out my mistake.