how to use fstream?

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());
  }
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.
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?
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 :)
That makes no sense. std::ifstream already uses the std::ios::in flag by default.
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...)
Uh, no. I've used std::ifstream with binary files thousands of times and I've never used the in flag.
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
It's not impossible. MinGW has given me some very weird behavior, in the past.
Topic archived. No new replies allowed.