Sign in to follow this  

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

This topic is 4397 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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?

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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)?

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

This topic is 4397 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this