c++fstreamturbo-c++

Weird problem with fstream. Cannot store objects with member variables having a certain value


When I try to store an object with any element having a value of 13 or 26 or 7 and then try to read this file, it simply gives garbage values. This doesn't happen with other values like 1, 64, 78 (random values).

I have used ofstream and ifstream separately to keep the code simple. I am using an old compiler (Borland C++) but my friends haven't encountered this error.

#include <iostream.h>
#include <conio.h>
#include <fstream.h>

class xyz
{
  public:
    int x;
};

void main()
{
    xyz a;
    a.x = 45; // replace by 45 or 78 it works. Replace by 13, 26 it shows garbage values.

    ofstream of;
    of.open("file.dat", ios::out||ios::binary);
    of.write((char*)&a, sizeof(a));
    of.close();

    xyz b;

    ifstream sf;
    sf.open("file.dat", ios::in||ios::binary);
    sf.read((char*)&b, sizeof(b));
    sf.close();

    cout<<b.x;
    getch();
}

Currently the output will be 45 but if you replace it by 13 or 26, it prints garbage values.


Solution

  • sf.open("file.dat", ios::in||ios::binary);
    

    || does not do what you think it does. Here, you need to use the bitwise or operator, |, and not || which is a logical operator.

    As a result, your files actually get opened in text mode, instead of binary mode as you intended, because of this mistake.

    Your code writes binary octets, 13 and 26, to the file and reads it back. Octets 13, and 26 have special meaning in text files on Microsoft Windows, due to its historical legacy. Your code also fails to check the return value from read() and/or the input stream's status, which would've allowed you to detect this error.