views:

99

answers:

4

I created this program:

#include <iostream>
#include <fstream>
using namespace std;

int main () {
  fstream file;
  file.open("test.bin", ios::in | ios::out | ios::binary);
  if(!file.is_open())
  {
      return -1;
  }
  int n = 5;
  int x;
  file.write(reinterpret_cast<char*>(&n), sizeof(n));
  file.read(reinterpret_cast<char*>(&x), sizeof(x));
  std::cout<<x;
  file.close();
  std::cin.ignore();
  return 0;
}

that's supposed to write an integer "n" into a .bin file "test.bin", then read data from "test.bin" into an integer "x", then displays "x" to the screen.

When I run the program, it displays not 5, but -842150451. Why does this occur, and how can I fix it?

+7  A: 

Isn't the file.write() moving the current file pointer when you write it, causing you to read data from the first location AFTER the written data?

Jherico
+1  A: 

You have to reposition the file stream to the start of the file after you do the write in order to read the data you just wrote.

You should also check that the write wrote everything you expected it to, and whether the read actually read anything at all. The semi-random number is due to the read failing.

Jonathan Leffler
+1  A: 

Insert file.seekg(0); between the read and write commands.

Billy ONeal
+1  A: 

I agree with Jherico. You need a:

file.seekg (0, ios::beg);
Robert Harvey
No ios::beg needed (seekg is overloaded)
Billy ONeal