📅 2013-Dec-27 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ binary, cpp, fstream ⬩ 📚 Archive
Let us assume you want to write the binary representation of variables of native data types (like
float) or objects to a file. Such a file can read back to recover the original values.
Writing a binary file can be done in 3 steps in C++:
fstream header file. This holds the classes and flags needed for the writing.
Create an object of the
ofstream class. This can be used to open the file and write to it. Open the object using the
binary flag. Contrary to expectation, opening this file in binary mode does not make the writing using
operator << become magically binary. All the
binary flag does it to prevent of special characters like EOL or EOF.
Write the bytes of the variable or object to the
Here is an example of writing a
float value to file:
#include <fstream> const float f = 3.14f; std::ofstream ofile("foobar.bin", std::ios::binary); char*) &f, sizeof(float));ofile.write((
The same method can be used to write objects. Note that if your object holds pointers to other data, then you need some sort of deep copy or serialization. This simple method to write to file will not work in such a case.