Writing to a binary file = copy to a binary file?

Started by
3 comments, last by jdhardy 18 years, 4 months ago
Is it possible to have a instance of a class write itself to a binary file but still be able to use that instance. Say for example I had

class ship
{
    public:
        void WriteToFile(const char *filename);
        int x, y;
};


void ship::WriteToFile(const char *filename)
{
    std::ofstream fout(filename, ios::binary);

    fout.write((char*) this, sizeof *this);

    fout.close();
}

So first off, can I even do this. Secondly, after I make a call to WriteToFile() are x and y the same as before I made the call. In other words, does this copy the class to the file or directly write it to the file?
Advertisement
For this simple example, it will work. However, you didn't include the code to read the file. There are cases where it won't work (for example, if the class has virtual functions or contains pointers).

I don't know what the difference is between "copy the class to the file" and "directly write it to the file", but x and y will not be changed by WriteToFile.
John BoltonLocomotive Games (THQ)Current Project: Destroy All Humans (Wii). IN STORES NOW!
I just didn't feel like writing #include's :) . I had thought about the pointers problem, but I completely forgot about virtual functions. So, what other options are there for saving the data members of a class to a file (without using text files)?
The ugly answer? By not just dumping the object to a file "as is". The least (ignoring virtual functions) is to replace pointers with id's. But seeing how a pointer already IS working as decent id (unless you consider it too large) you should only make sure to store the address of a referenced object along with it. Or of course just replace the pointer with the actual object.
f@dzhttp://festini.device-zero.de
C++ FAQ on Serialization. Synopsis: it's easy in the simple case, and very hard in the general case.

See also Boost.Serialization.

This topic is closed to new replies.

Advertisement