I’m having a simple file save/load functionality, but as it’s a plugin, due to host API everything is being written into std::ostream in binary format, and read back again from std::istream.
i use
out.write((char *)&value,sizeof(type));
in.read((char *)&value,sizeof(type));
for reading and writing, where type is “unsigned int”, “double”, etc.
I was thinking about possible consequences of this, what happens when file is saved on one platform, and loaded on another (due to host limitations, this will be a 32/64 bit windows, 64bit linux and 64bit mac, only x86 cpus). if I do not use variable-size type, like size_t (which is different on 32bit and 64bit systems), can I be certain that “unsigned int” or “double” will stay same length? Is there any best-practices to handle this?
No. Even the size of
unsigned intanddoublecould vary across platforms.Yes. Serialize the data.
For example, you could follow these steps:
Nnumber of bytes, whereN = sizeof(value), then write each byte, one by one – either from low signigicant byte to high significant byte, or vice versa.If you’re writing lots of values, then you may want to improve the above steps: the first and foremost you would not want to write the size for each value, for it is simply a repetition, instead you can write a header sort of things which contains all these information which is going to be used repeatedly.