C++ · Module 16 · Lesson 31 min read

Binary Files

Opening in binary mode

c
std::ofstream out("data.bin", std::ios::binary);
std::ifstream in("data.bin", std::ios::binary);

Writing and reading raw bytes

arduino
out.write(reinterpret_cast<const char*>(&record), sizeof(record));
in.read(reinterpret_cast<char*>(&record), sizeof(record));
if (in.gcount() != sizeof(record)) { /* incomplete */ }

Vectors of simple records:

arduino
out.write(reinterpret_cast<const char*>(v.data()), v.size() * sizeof(Record));

⚠️ Only for trivially copyable types

Raw write only works for plain data (int, double, char arrays, structs of those). Never for types containing std::string, std::vector, pointers or virtual functions — you'd save addresses, not data. Check with static_assert(std::is_trivially_copyable_v<Record>).

For strings, write the length first, then the characters.

Seeking (random access)

FunctionMeaning
seekg(pos) / tellg()move/get the read position
seekp(pos) / tellp()move/get the write position
seekg(0, std::ios::end)jump to the end (then tellg() = file size)
Record n starts at byte n * sizeof(Record) → jump straight to it and update it in place with std::fstream (`inout

Portability issues

  • Endianness (byte order) differs between some CPUs
  • Padding and type sizes can differ between compilers → use <cstdint> fixed-width types
  • Include a header: magic number + format version + record count

Text vs binary

TextBinary
Human-readable, editableCompact, fast, exact
PortablePlatform/format-specific
Numbers converted to digitsBytes copied directly

Example

C++
#include <cstdint>
#include <cstring>
#include <fstream>
#include <iostream>
#include <string>
#include <type_traits>
#include <vector>

struct Record {
    std::int32_t id;
    char category[16];
    double amount;
};
static_assert(std::is_trivially_copyable_v<Record>, "Record must be plain data for raw binary I/O");

struct Header {
    char magic[4];
    std::uint32_t version;
    std::uint32_t count;
};

Record make(int id, const char* cat, double amount) {
    Record r{};
    r.id = id;
    std::strncpy(r.category, cat, sizeof r.category - 1);
    r.amount = amount;
    return r;
}

int main() {
    std::vector<Record> records = { make(1, "Rent", 15000), make(2, "Food", 450.5), make(3, "Travel", 300) };
    {
        std::ofstream out("expenses.bin", std::ios::binary);
        Header h{ { 'B', 'B', 'D', 'Y' }, 1, static_cast<std::uint32_t>(records.size()) };
        out.write(reinterpret_cast<const char*>(&h), sizeof h);
        out.write(reinterpret_cast<const char*>(records.data()), static_cast<std::streamsize>(records.size() * sizeof(Record)));
    }

    std::ifstream in("expenses.bin", std::ios::binary);
    in.seekg(0, std::ios::end);
    std::cout << "file size: " << in.tellg() << " bytes (header " << sizeof(Header)
              << " + " << records.size() << " x " << sizeof(Record) << ")\n";
    in.seekg(0);

    Header h{};
    in.read(reinterpret_cast<char*>(&h), sizeof h);
    if (std::string(h.magic, 4) != "BBDY") { std::cout << "not our file!\n"; return 1; }
    std::vector<Record> loaded(h.count);
    in.read(reinterpret_cast<char*>(loaded.data()), static_cast<std::streamsize>(h.count * sizeof(Record)));
    std::cout << "version " << h.version << ", loaded " << loaded.size() << " records:\n";
    for (const auto& r : loaded) std::cout << "  #" << r.id << ' ' << r.category << ' ' << r.amount << '\n';
    in.close();

    // update record #2 in place (random access)
    std::fstream io("expenses.bin", std::ios::in | std::ios::out | std::ios::binary);
    std::streamoff offset = sizeof(Header) + 1 * sizeof(Record);
    Record r{};
    io.seekg(offset);
    io.read(reinterpret_cast<char*>(&r), sizeof r);
    r.amount = 999.99;
    io.seekp(offset);
    io.write(reinterpret_cast<const char*>(&r), sizeof r);
    io.seekg(offset);
    io.read(reinterpret_cast<char*>(&r), sizeof r);
    std::cout << "record #2 after in-place update: " << r.category << ' ' << r.amount << '\n';
    return 0;
}

/* Output:
file size: 108 bytes (header 12 + 3 x 32)
version 1, loaded 3 records:
  #1 Rent 15000
  #2 Food 450.5
  #3 Travel 300
record #2 after in-place update: Food 999.99
*/