how to use fstream?

Oct 24, 2009 at 11:01pm
hi guys,

My point is to make a program that could read from given file byte by byte.. somehow it turned out for me not to be as easy so i simplified my code till it became the fraction below. The thing is that my ifstream object stops reading at some point and returns just 0xFF bytes until the end of the reading. Most probably I just don't properly understand the function of this stream. In the case you saw where is the problem, please let me know, you would probably save at least one day of my life.thx

1
2
3
4
5
6
7
8
9
10
  ifstream fin("data");
  ofstream fout("output");
  
  fin.seekg (0, ios::end);
  int length = fin.tellg();
  fin.seekg (0, ios::beg);

  for(int i=0;i<length;i++){
    fout.put(fin.get());
  }
Oct 24, 2009 at 11:27pm
You need to open the file as binary, otherwise, it's opened as text and fstream does some pretty annoying things.
std::ifstream fin("data",std::ios::binary);

By the way, it's much more common to read the entire file or chunks thereof into a an array, than read it byte by byte. It's a lot faster.
Oct 25, 2009 at 9:13am
I tried to open it as binary, but already the first byte threw failbit and eofbit. When I removed that ios::binary ... flag? it worked for that incomplete part again. Btw about the speed I thought there is automaticaly initialized some filebuffer.. or do I need to create some explicitly?
Oct 25, 2009 at 6:12pm
ok, problem solved!!

so for others who should ever have this problem, if initializing ifstream for reading binary files like this

ifstream fin("data", ios::binary);

don't forget to add the other flag for input stream, so if the previous way is throwing error flags you need to initialize it as:

ifstream fin("data", ios::in | ios::binary);

then it should work...

if anyone felt like.. willing to explain why is that, I would be most pleased to find it out so.. please dont be shy and post it :)
Oct 25, 2009 at 6:19pm
That makes no sense. std::ifstream already uses the std::ios::in flag by default.
Oct 25, 2009 at 7:41pm
explicit ifstream ( const char * filename, ios_base::openmode mode = ios_base::in );

So theoretically, if you just change it ios:binary, you will lose the ios::in (however stupid that seems...)
Oct 25, 2009 at 7:57pm
Uh, no. I've used std::ifstream with binary files thousands of times and I've never used the in flag.
Oct 29, 2009 at 9:55pm
could it be that i use g++ on windows? you know... it has it's own include files.. so maybe that's why it behaves so sucky
Oct 29, 2009 at 9:59pm
It's not impossible. MinGW has given me some very weird behavior, in the past.
Oct 30, 2009 at 7:00am
Topic archived. No new replies allowed.