C++
Binary serialization
Learn to write objects to files with binary serialization.
What is binary serialization?
Binary serialization writes an object's memory content byte by byte to a file. It is not human readable but is fast and compact. In C++ you open an std::ofstream in std::ios::binary mode and use the write method.
Example: std::ofstream ofs("data.bin", std::ios::binary); ofs.write(reinterpret_cast<const char*>(&value), sizeof(value));. Here reinterpret_cast lets us treat the value as a byte array; sizeof(value) is the byte count. To read back, use std::ifstream with the read method. This approach is simple but layout specific: a different compiler's memory layout can break it.
sizeof and reinterpret_cast
Binary writing needs two things: the data address and its size. You get the address with reinterpret_cast<const char*>(&value); it treats the value as a byte pointer. The size is given by sizeof(value).
For example an int is 4 bytes. ofs.write(reinterpret_cast<const char*>(&n), sizeof(n)); writes exactly 4 bytes. Reading back uses the same approach: ifs.read(reinterpret_cast<char*>(&n), sizeof(n));. Here char* (without const) is used because the read data is written into the variable. Repeating this for each field serializes the whole struct.
Exercise Write and read a binary file
Define int value = 42;. Open std::ofstream ofs("data.bin", std::ios::binary) and write with ofs.write(reinterpret_cast<const char*>(&value), sizeof(value)). Then open std::ifstream ifs("data.bin", std::ios::binary) and read with ifs.read(reinterpret_cast<char*>(&loaded), sizeof(loaded)). Print the loaded value with std::cout.
Show example solution
#include <iostream>
#include <fstream>
int main() {
int value = 42;
std::ofstream ofs("data.bin", std::ios::binary);
ofs.write(reinterpret_cast<const char*>(&value), sizeof(value));
ofs.close();
int loaded = 0;
std::ifstream ifs("data.bin", std::ios::binary);
ifs.read(reinterpret_cast<char*>(&loaded), sizeof(loaded));
ifs.close();
std::cout << loaded;
return 0;
}
Test yourself
-
Complete the binary mode
std::ofstream ofs("data.bin", std::ios::____);
Show answer
std::ofstream ofs("data.bin", std::ios::binary);
-
What is the advantage of binary serialization?
- Being faster and more compact
- Being human readable
- Being cross platform
- Being editable in a text editor
Show answer
Being faster and more compact — Binary is faster and takes less space than text.
-
Match each piece to its role
- std::ios::binary
- Binary mode
- ofs.write(...)
- Writes bytes
- ifs.read(...)
- Reads bytes
- reinterpret_cast
- Casts to byte pointer
Next lesson: Text serialization