user98188
user98188

Reputation:

Why doesn't this program read (or write?) correctly from a .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;
}

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?

Upvotes: 0

Views: 215

Answers (4)

Robert Harvey
Robert Harvey

Reputation: 180868

I agree with Jherico. You need a:

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

Upvotes: 1

Billy ONeal
Billy ONeal

Reputation: 106599

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

Upvotes: 2

Jonathan Leffler
Jonathan Leffler

Reputation: 754570

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.

Upvotes: 1

Jherico
Jherico

Reputation: 29240

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?

Upvotes: 7

Related Questions