The binary file changes the rules in one important way. The bytes that you give to the stream are the bytes that go into the file, unchanged. There is no translation of the line endings and no formatting of the values. That makes the format exact, and it makes the portability your responsibility.
The previous lesson in this module covered "How Do ifstream and ofstream Read and Write Files?", and the next lesson in this module is about "How Does main Receive Command-Line Arguments?".
Writing raw bytes
A stream in the binary mode writes the bytes that you give it, unchanged.
#include <fstream>
#include <iostream>
int main() {
std::ofstream file("readings.bin", std::ios::binary);
if (!file) {
std::cerr << "could not open readings.bin\n";
return 1;
}
const int values[3] = {42, 91, 12};
file.write(reinterpret_cast<const char*>(values), sizeof(values));
file.close();
std::cout << "wrote " << sizeof(values) << " bytes\n";
return 0;
}The output shows the twelve bytes that were written, which are three integers of four bytes each.
wrote 12 bytesReading raw bytes
The read() fills a buffer and it reports how many bytes it actually got.
#include <fstream>
#include <iostream>
int main() {
std::ifstream file("readings.bin", std::ios::binary);
if (!file) {
std::cerr << "could not open readings.bin\n";
return 1;
}
int values[3] = {0, 0, 0};
file.read(reinterpret_cast<char*>(values), sizeof(values));
std::cout << "bytes read: " << file.gcount() << '\n';
for (int value : values) {
std::cout << value << ' ';
}
std::cout << '\n';
return 0;
}The output shows the three values recovered exactly.
bytes read: 12
42 91 12Writing a struct
A struct of the plain data can be written directly, and that makes a binary format very easy to define.
#include <cstdint>
#include <fstream>
#include <iostream>
struct Reading {
std::int32_t sensor_id;
std::int32_t value;
double timestamp;
};
int main() {
std::ofstream file("reading.bin", std::ios::binary);
if (!file) {
std::cerr << "could not open reading.bin\n";
return 1;
}
Reading reading{7, 91, 12345.5};
file.write(reinterpret_cast<const char*>(&reading), sizeof(reading));
file.close();
std::ifstream check("reading.bin", std::ios::binary);
Reading loaded{0, 0, 0.0};
check.read(reinterpret_cast<char*>(&loaded), sizeof(loaded));
std::cout << "sensor: " << loaded.sensor_id << '\n';
std::cout << "value: " << loaded.value << '\n';
std::cout << "time: " << loaded.timestamp << '\n';
return 0;
}The output shows the struct recovered field by field.
sensor: 7
value: 91
time: 12345.5Writing a portable format
The safe alternative is to define the format explicitly, with the fixed-width integers, a documented field order and no padding.
#include <cstdint>
#include <fstream>
#include <iostream>
void write_u32(std::ofstream& file, std::uint32_t value) {
unsigned char bytes[4] = {
static_cast<unsigned char>((value >> 24) & 0xFF),
static_cast<unsigned char>((value >> 16) & 0xFF),
static_cast<unsigned char>((value >> 8) & 0xFF),
static_cast<unsigned char>(value & 0xFF)
};
file.write(reinterpret_cast<const char*>(bytes), 4);
}
std::uint32_t read_u32(std::ifstream& file) {
unsigned char bytes[4] = {0, 0, 0, 0};
file.read(reinterpret_cast<char*>(bytes), 4);
return (static_cast<std::uint32_t>(bytes[0]) << 24) |
(static_cast<std::uint32_t>(bytes[1]) << 16) |
(static_cast<std::uint32_t>(bytes[2]) << 8) |
static_cast<std::uint32_t>(bytes[3]);
}
int main() {
std::ofstream file("portable.bin", std::ios::binary);
write_u32(file, 4821);
file.close();
std::ifstream check("portable.bin", std::ios::binary);
std::cout << "value: " << read_u32(check) << '\n';
return 0;
}The output shows the value surviving the round trip.
value: 4821What binary files are good for
They are good for the fixed-size records, because a record sits at a known offset, so you can seek straight to it.
#include <fstream>
#include <iostream>
int main() {
std::ofstream file("table.bin", std::ios::binary);
for (int i = 0; i < 10; ++i) {
int value = i * i;
file.write(reinterpret_cast<const char*>(&value), sizeof(value));
}
file.close();
std::ifstream check("table.bin", std::ios::binary);
check.seekg(4 * sizeof(int), std::ios::beg); // the fifth record
int value = 0;
check.read(reinterpret_cast<char*>(&value), sizeof(value));
std::cout << "fifth value: " << value << '\n';
return 0;
}The output shows the fifth record read directly by seeking to its offset.
fifth value: 16What binary files cost you
They cost you the portability, because the layout of a struct is decided by the compiler and it can differ between the systems. They also cost you the readability, because a person cannot look at the file and see what is in it. And they cost you the version number, because a file that was written by an older version of the program may not be readable by the newer one.
And that is why a text format is the better choice when the data is small, when the people have to read it, or when it has to survive a change of the compiler. You use a binary format when the data is large, when the speed matters, or when the format is fixed once and for all.
Quick reference
- The binary mode writes the bytes unchanged, with no translation and no formatting.
- You use the
write()and theread()with the size in the bytes. - The
gcount()tells you how many bytes the last read actually got. - Writing a struct directly is easy, but the layout is the compiler's choice and it is not portable.
- You define a portable format with the fixed-width integers and a documented field order.
- Use a binary file for the large fixed-size records, and a text file for everything else.
Try it yourself: write an array of three integers to a binary file and read them back. Then write a struct with an int and a double, and read it back, and check the size of the struct. Finally, write a value by hand with the fixed-width helper and read it with the matching one, and confirm that it survives the round trip.