Cannot read simple binary integers from file? (C++)

John S. picture John S. · Jun 7, 2011 · Viewed 7.3k times · Source

My code is simply as this:

UPDATED:

#include <iostream>
#include <fstream>

using namespace std;

int main(int argc, char **argv)
{
  ifstream r("foo.bin", ios::binary);
  ofstream w("foo.bin", ios::binary);
  int i;

  int ints[10] = {0,1,2,3,4,5,6,8,9};
  w.write((char*)&ints, sizeof(ints));

  int in_ints[10];
  r.read((char*)&in_ints, sizeof(in_ints));

  for(i = 0;i < 10;i++) {
    cout << in_ints[i] << " ";
  }
  cout << endl;

  return 0;
}

Now, the write portion appears to be successful, for example running the od command with 32 bit longs (my system is 32 bit) will display the correct sequence, including a hex dump.

Reading however, I get random sequences such and negative integers that should not happen (it is split up, and mostly zeros as my integers are small, the sign bits should not be on.)

Do you see why my read method has failed to work, when it is really an opposite of my write method?

Answer

Ali1S232 picture Ali1S232 · Jun 7, 2011

try w.flush() or w.close() before r.read. the problem is when you write it usually bufferes text and doesn't save it in file. so there is nothing realy in file for r.read.