A simple serialization header

A simple binary serialization header

For convenience, its often handy to read and write data to disk in binary format. What we need to do is cast ever variable we wish to write to byte format. We therefore cast each variable to a char which is of size 1 byte and write it to disk. This is the header, just include it in your code:

// convenience code for serializing a variable to disk / reading in a var from disk
// Ben Jones 2011


#include <iostream>
#include <fstream>

template <class T>
void serializeVariable(T var, std::ofstream &outFile)
    outFile.write (reinterpret_cast < char *>(&var),sizeof (var));

template <class T>
void readSerializedVariable(T &var, std::ifstream &inFile)
{ (reinterpret_cast < char *>(&var),sizeof (var));


to use this code, simply include it, say you have a class called Bob and a function called serialize, you’d do something like

#include "serializer.h"

Bob::serialize(ofstream& outFile)

in order to write an integer variable called integerVariable and a double variable called doubleVariable to disk.