Lesson 37 +40 XP

Persistent Objects: Reading and Writing Objects in Files

Persistent Objects: Reading and Writing Objects in Files

An ordinary object lives only while the program runs: when its scope ends or the program exits, it is gone. A persistent object is one whose state outlives the program that created it: it is saved to a file (or database) and can be restored later, even by another run of the program. This lesson shows how C++ makes objects persistent using binary files with write() and read(), how to update records in place with random access, and the limits of this simple approach.

1. Transient vs Persistent Objects

Transient objectPersistent object
exists only in memory while the program runsits state is stored on disk
destroyed at the end of its scope or of the programsurvives after the program ends
example: a local Student in maina Student record saved in students.dat and loaded again next time

C++ has no built-in persistence: the programmer writes the code to save an object's state (serialisation) and to rebuild an object from the saved data (deserialisation). The two basic tools are the binary write() and read() functions of the file streams.

2. Binary I/O with write() and read()

C++
outfile.write((char*)&object, sizeof(object));
infile.read((char*)&object, sizeof(object));
  • The first argument is the address of the data, cast to char* (a byte pointer).
  • The second is the number of bytes: sizeof(object).
  • The data is copied byte for byte, exactly as it is stored in memory: no conversion to text, so it is fast and exact.
  • The file should be opened with ios::binary.

Only the object's data members are written. Member functions are not stored (they are code, shared by all objects).

Writing and reading numbers in binary

C++
#include <iostream>
#include <fstream>
using namespace std;

int main() {
    float height[4] = {175.5, 153.0, 167.25, 160.7};

    ofstream out("heights.dat", ios::binary);
    out.write((char*)height, sizeof(height)); // 16 bytes in one call
    out.close();

    for (int i = 0; i < 4; i++) {
        height[i] = 0; // wipe the array
    }

    ifstream in("heights.dat", ios::binary);
    in.read((char*)height, sizeof(height)); // restore it from the file
    in.close();

    for (int i = 0; i < 4; i++) {
        cout << height[i] << " ";
    }
    cout << endl;
    return 0;
}

Output:

OUTPUT
175.5 153 167.25 160.7 

3. Writing and Reading Class Objects

C++
#include <iostream>
#include <fstream>
#include <cstring>
#include <iomanip>
using namespace std;

class Inventory {
    char name[20];
    int code;
    float cost;

public:
    Inventory() {
        name[0] = '\0';
        code = 0;
        cost = 0;
    }
    Inventory(const char* n, int c, float p) {
        strncpy(name, n, 19);
        name[19] = '\0';
        code = c;
        cost = p;
    }
    void show() const {
        cout << setw(10) << name << setw(8) << code << setw(10) << fixed << setprecision(2) << cost
             << endl;
    }
};

int main() {
    Inventory items[3] = {Inventory("Monitor", 101, 8500), Inventory("Keyboard", 102, 799.5),
                          Inventory("Mouse", 103, 349)};

    ofstream out("stock.dat", ios::binary);
    for (int i = 0; i < 3; i++) {
        out.write((char*)&items[i], sizeof(Inventory)); // save each object
    }
    out.close();
    cout << "Saved " << 3 << " objects of " << sizeof(Inventory) << " bytes each" << endl;

    // A later run (or another program) restores them:
    ifstream in("stock.dat", ios::binary);
    Inventory item;
    cout << setw(10) << "NAME" << setw(8) << "CODE" << setw(10) << "COST" << endl;
    while (in.read((char*)&item, sizeof(Inventory))) { // one object per read
        item.show();
    }
    in.close();
    return 0;
}

Output:

OUTPUT
Saved 3 objects of 28 bytes each
      NAME    CODE      COST
   Monitor     101   8500.00
  Keyboard     102    799.50
     Mouse     103    349.00

4. Updating a Persistent Object in Place (Random Access)

Because every object occupies exactly sizeof(Inventory) bytes, the n-th object starts at byte

location = (n - 1) × texttt{sizeof(object)}

So the program can jump straight to it with seekg/seekp, read it, change it and write it back, without touching the other records. The file is opened with fstream in ios::in | ios::out | ios::binary mode.

C++
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;

class Account {
    int number;
    char holder[16];
    double balance;

public:
    Account() {
        number = 0;
        holder[0] = '\0';
        balance = 0;
    }
    Account(int n, const char* h, double b) {
        number = n;
        strncpy(holder, h, 15);
        holder[15] = '\0';
        balance = b;
    }
    void deposit(double amt) {
        balance = balance + amt;
    }
    void show() const {
        cout << number << " " << holder << " " << balance << endl;
    }
};

int main() {
    fstream file("accounts.dat", ios::in | ios::out | ios::binary | ios::trunc);
    Account a1(1, "Asha", 5000), a2(2, "Bilal", 7200), a3(3, "Chen", 300);
    file.write((char*)&a1, sizeof(Account));
    file.write((char*)&a2, sizeof(Account));
    file.write((char*)&a3, sizeof(Account));

    file.seekg(0, ios::end);
    int count = file.tellg() / sizeof(Account);
    cout << "records in file: " << count << endl;

    // update record 2 only
    int n = 2;
    long location = (n - 1) * sizeof(Account);
    Account acc;
    file.seekg(location, ios::beg);
    file.read((char*)&acc, sizeof(Account));
    acc.deposit(800);
    file.seekp(location, ios::beg);           // go back to the same place
    file.write((char*)&acc, sizeof(Account)); // overwrite just this record

    // show all records
    file.seekg(0, ios::beg);
    while (file.read((char*)&acc, sizeof(Account))) {
        acc.show();
    }
    file.close();
    return 0;
}

Output:

OUTPUT
records in file: 3
1 Asha 5000
2 Bilal 8000
3 Chen 300

5. Persistence Functions Inside the Class

A cleaner design gives the class its own save() and load() member functions. The rest of the program then does not need to know how the object is stored, which is encapsulation applied to persistence.

C++
#include <iostream>
#include <fstream>
#include <cstring>
#include <cstdio>
using namespace std;

class Student {
    int roll;
    char name[20];
    float cgpa;

public:
    Student() {
        roll = 0;
        name[0] = '\0';
        cgpa = 0;
    }
    Student(int r, const char* n, float c) {
        roll = r;
        strncpy(name, n, 19);
        name[19] = '\0';
        cgpa = c;
    }
    bool save(const char* file) const { // serialise
        ofstream out(file, ios::binary | ios::app);
        if (!out) {
            return false;
        }
        out.write((const char*)this, sizeof(*this)); // 'this' points to the object
        return true;
    }
    bool load(ifstream& in) { // deserialise the next record
        return (bool)in.read((char*)this, sizeof(*this));
    }
    void show() const {
        cout << roll << ". " << name << " (CGPA " << cgpa << ")" << endl;
    }
};

int main() {
    remove("class.dat"); // start with an empty file
    Student(1, "Isha", 9.1f).save("class.dat");
    Student(2, "Kunal", 8.4f).save("class.dat");
    Student(3, "Mira", 8.9f).save("class.dat");

    ifstream in("class.dat", ios::binary);
    Student s;
    while (s.load(in)) {
        s.show();
    }
    return 0;
}

Output:

OUTPUT
1. Isha (CGPA 9.1)
2. Kunal (CGPA 8.4)
3. Mira (CGPA 8.9)

6. Limits of Binary Object Persistence

Writing raw object bytes is simple and fast, but it works only for simple classes:

ProblemWhy
Pointer membersthe address is saved, not the data it points to; after reloading, the pointer is meaningless. A char* name or a string member cannot be saved this way
Virtual functionsthe hidden vptr is saved too; it is only valid in the run that wrote it
Portabilitysizeof, byte order (endianness) and padding differ between compilers and machines, so a file written on one system may not read correctly on another
Changing the classadding a member changes sizeof, so old files no longer match

For such classes, each data member is written individually (for a string: its length followed by its characters), in a fixed, documented format. This is serialisation in the full sense; libraries and databases do it on a large scale.

💡 Tip

Key points to remember

  • A persistent object's state is saved to a file and restored later; C++ has no automatic persistence.
  • Binary I/O: out.write((char*)&obj, sizeof(obj)); and in.read((char*)&obj, sizeof(obj)); with ios::binary.
  • Only data members are saved; member functions are not.
  • The n-th record starts at (n - 1) * sizeof(obj): use seekg/seekp to update it in place.
  • Raw byte saving fails for pointer members, virtual functions and different platforms; such classes need member-by-member serialisation.
🎯 END-TERM EXAM PREP

📝 IPU End-Term Exam Corner (5-10 Marks)

  • Q1. What are persistent objects? How are objects written to and read from a file in C++? (10 Marks)
  • Write: transient vs persistent, the write()/read() syntax, and the Inventory program with output.
  • Q2. Write a program to update a particular record in a binary file of objects. (10 Marks)
  • Write: the location formula, the Account program using seekg/seekp, and its output.
  • Q3. Explain the read() and write() functions. Why is ios::binary used? (5 Marks)
  • Q4. What are the limitations of storing objects as raw bytes? (2.5 Marks)