Skip to content

Instantly share code, notes, and snippets.

@IgorYunusov
Forked from codemonkey85/objSerialization.cpp
Created December 24, 2017 08:23
Show Gist options
  • Save IgorYunusov/fc5652df0804299305cea6b9100d6f00 to your computer and use it in GitHub Desktop.
Save IgorYunusov/fc5652df0804299305cea6b9100d6f00 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();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment