Skip to main content

File stream; student binary file program

Short answer

A file stream connects a program to a disk file. The Student class uses ofstream (binary, append) to write the object directly, and ifstream (binary) to read records. To search by roll, loop reading records; if roll matches, display the record.

What is a file stream? Write a class student with roll, name, address, marks as member variables. Use a member function to write records of students in a binary file and another member function to read records from file. Write a program to search a specific record of student using roll number as key from user input.

File stream

A file stream is a stream that connects a program to a disk file so that data can be read from or written to it using the normal I/O operators and functions. C++ provides ifstream (input), ofstream (output) and fstream (both) in <fstream>.

Program

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

class Student {
    int roll;
    char name[30], address[30];
    float marks;
public:
    void getData() {
        cout << "Roll, Name, Address, Marks: ";
        cin >> roll >> name >> address >> marks;
    }
    void display() {
        cout << roll << "\t" << name << "\t" << address
             << "\t" << marks << endl;
    }
    int getRoll() { return roll; }

    void writeRecord() {                       // write one record
        ofstream fout("student.dat", ios::binary | ios::app);
        fout.write((char*)this, sizeof(*this));
        fout.close();
    }
    void readRecords() {                       // read all records
        ifstream fin("student.dat", ios::binary);
        while (fin.read((char*)this, sizeof(*this)))
            display();
        fin.close();
    }
};

int main() {
    Student s;
    int n;
    cout << "How many students? ";
    cin >> n;
    for (int i = 0; i < n; i++) {
        s.getData();
        s.writeRecord();
    }

    cout << "\nAll records:\n";
    s.readRecords();

    int key;
    bool found = false;
    cout << "\nEnter roll number to search: ";
    cin >> key;
    ifstream fin("student.dat", ios::binary);
    while (fin.read((char*)&s, sizeof(s))) {
        if (s.getRoll() == key) {
            cout << "Record found:\n";
            s.display();
            found = true;
            break;
        }
    }
    fin.close();
    if (!found) cout << "Record not found\n";
    return 0;
}

Binary mode stores each object exactly as it is in memory, so every record has the same size and can be read back with read() in one step. Character arrays are used instead of string so the records contain no pointers.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Object Oriented Programming chapter 8 questions →