Why doesn't this program read (or write?) Correctly from the .bin file? (C ++)

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;
}

      

which should write the integer "n" to the .bin file "test.bin", then read the data from "test.bin" into the integer "x", and then display the "x" on the screen.

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

0


a source to share


4 answers


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



+7


a source


Paste file.seekg(0);

between read and write commands.



+2


a source


You have to move the file stream to the beginning of the file after writing in order to read the data you just wrote.

You should also check that the post has written everything that you expected, and if it read anything at all. The semi-random number is due to a read error.

+1


a source


I agree with Jericho. You will need:

file.seekg (0, ios::beg);

      

+1


a source







All Articles