Skip to content

Instantly share code, notes, and snippets.

@codemonkey85
Last active November 26, 2022 04:26
Show Gist options
  • Save codemonkey85/5860625 to your computer and use it in GitHub Desktop.
Save codemonkey85/5860625 to your computer and use it in GitHub Desktop.
An example of how to serialize / deserialize a C++ struct to and from a disk file.
struct OBJECT{ // The object to be serialized / deserialized
public:
// Members are serialized / deserialized in the order they are declared. Can use bitpacking as well.
DATATYPE member1;
DATATYPE member2;
DATATYPE member3;
DATATYPE member4;
};
void write(const std::string& file_name, OBJECT& data) // Writes the given OBJECT data to the given file name.
{
std::ofstream out;
out.open(file_name,std::ios::binary);
out.write(reinterpret_cast<char*>(&data), sizeof(OBJECT));
out.close();
};
void read(const std::string& file_name, OBJECT& data) // Reads the given file and assigns the data to the given OBJECT.
{
std::ifstream in;
in.open(file_name,std::ios::binary);
in.read(reinterpret_cast<char*>(&data), sizeof(OBJECT));
in.close();
};
@danemo01
Copy link

danemo01 commented Jun 2, 2018

From what I know, this example showcase no way of serializing or de-serializing and object. More of how to read and write binary files.

Or perhaps read/write function already serialize and de-serialize the object?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment