C++ · Module 16 · Lesson 51 min read

Saving & Loading Objects (Serialization)

Serialization

Serialize: object → bytes/text (to save or send). Deserialize: bytes/text → object.

Approach 1: overload << and >> ✅ (simple text format)

c
std::ostream& operator<<(std::ostream& os, const Expense& e) {
    return os << std::quoted(e.note) << ' ' << e.amount << ' ' << e.day;
}
std::istream& operator>>(std::istream& is, Expense& e) {
    return is >> std::quoted(e.note) >> e.amount >> e.day;
}
  • Works with files and string streams (great for testing)
  • std::quoted (<iomanip>) writes strings in quotes and escapes inner quotes, so notes may contain spaces

Saving a collection

Write a count (or a version line) first, then each item:

csharp
out << "BUDGET v1\n" << items.size() << '\n';
for (const auto& e : items) out << e << '\n';

Reading back: check the header, read the count, then loop.

Versioning

Put a format version in the header. When fields are added later, the loader can still read old files (e.g. use defaults for missing fields).

Robustness checklist

  • Validate everything you read (counts, ranges)
  • Fail gracefully on corrupted files — never crash
  • Write to a temporary file, then rename over the old file, so a crash mid-save can't destroy the existing data ✅
  • Round-trip test: save → load → compare equal

Other formats

FormatWhen
CSVtables, spreadsheets
JSONAPIs, config, mobile apps — libraries: nlohmann/json, simdjson, RapidJSON
Binaryspeed/size (lesson 16.3); protocol buffers, FlatBuffers for cross-language
SQLitemany records, queries, safe concurrent updates

Example

C++
#include <filesystem>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>

struct Expense {
    std::string note;
    double amount = 0;
    int day = 1;
    bool operator==(const Expense&) const = default;
};

std::ostream& operator<<(std::ostream& os, const Expense& e) {
    return os << std::quoted(e.note) << ' ' << e.amount << ' ' << e.day;
}
std::istream& operator>>(std::istream& is, Expense& e) {
    Expense tmp;
    if (is >> std::quoted(tmp.note) >> tmp.amount >> tmp.day) {
        if (tmp.amount <= 0 || tmp.day < 1 || tmp.day > 31) is.setstate(std::ios::failbit);   // validate
        else e = tmp;
    }
    return is;
}

bool save(const std::vector<Expense>& items, const std::string& path) {
    const std::string tmp = path + ".tmp";
    {
        std::ofstream out(tmp);
        if (!out) return false;
        out << "BUDGET v1\n" << items.size() << '\n';
        for (const auto& e : items) out << e << '\n';
        if (!out) return false;
    }
    std::filesystem::rename(tmp, path);          // replace the old file in one step
    return true;
}

std::vector<Expense> load(std::istream& in) {
    std::string header;
    std::size_t count = 0;
    if (!std::getline(in, header) || header != "BUDGET v1" || !(in >> count) || count > 100000)
        throw std::runtime_error("not a valid budget file");
    std::vector<Expense> items;
    for (std::size_t i = 0; i < count; ++i) {
        Expense e;
        if (!(in >> e)) throw std::runtime_error("corrupted record " + std::to_string(i + 1));
        items.push_back(e);
    }
    return items;
}

int main() {
    std::vector<Expense> items = { { "Rent for \"Lakeside\" flat", 15000, 1 }, { "momo lunch", 450.5, 3 } };
    std::cout << "one record as text: " << items[0] << '\n';

    save(items, "budget.txt");
    std::ifstream in("budget.txt");
    auto loaded = load(in);
    std::cout << "loaded " << loaded.size() << " records; round trip equal? " << std::boolalpha << (loaded == items) << '\n';
    std::cout << "note with quotes survived: " << loaded[0].note << '\n';

    std::istringstream corrupted("BUDGET v1\n2\n\"ok\" 100 5\n\"bad day\" 50 45\n");
    try {
        load(corrupted);
    } catch (const std::exception& e) {
        std::cout << "error: " << e.what() << '\n';
    }
    std::istringstream wrong("hello world");
    try {
        load(wrong);
    } catch (const std::exception& e) {
        std::cout << "error: " << e.what() << '\n';
    }
    std::filesystem::remove("budget.txt");
    return 0;
}

/* Output:
one record as text: "Rent for \"Lakeside\" flat" 15000 1
loaded 2 records; round trip equal? true
note with quotes survived: Rent for "Lakeside" flat
error: corrupted record 2
error: not a valid budget file
*/