Last active
November 26, 2022 04:26
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
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?