简体   繁体   中英

How would I write a class object to a file?

Alright, I have an object:

LivingObject* myPlayer=new LivingObject(...);

And I would like to write it to a file on exit. Here is what I have so far:

std::fstream myWrite;
myWrite.open("Character.dat",std::ios::binary|std::ios::app);
myWrite.write((char*)myPlayer,sizeof(myPlayer));
myWrite.close();

I watched over the file when exiting and the size did not increase at all(me assuming it didnt write). What did I do wrong?

This code writes the only the first 4 (or 8 in 64 bits) bytes of the object to file not the whole object. To write the whole object use:

myWrite.write((char*)myPlayer,sizeof(LivingObject));

As for the size of the file: some operating systems report file size as the space allocated to the file on disk, which is multiple of the physical block size. So as long as the write did not increase beyond the block size, you will not see an increase of the file size.

myPlayer is a pointer to a LivingObject

myWrite.write((char*)myPlayer,sizeof(myPlayer)); This line, you're casting a pointer to another pointer, and then saying the sizeof a pointer type (which is usually 4). So you'd be writing 4 bytes of data (the address), and not the object instead.

So instead, what you'll need to do is to serialize the class, either to a binary packed format, or another format (XML, JSON etc), and write that to the file.

Search the web for "boost serialize". The operation you are performing is called serialization.

If you want to share data between platforms, you will need to either choose a format that is not binary or write down the format, be sure to mention which multi-byte quanties are Little Endian or Big Endian.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM