Skip to main content

Student file read/write and modify by roll

Short answer

Write 10 student records to binary file student.dat. To modify by roll number, open in read/write mode, scan records with read(). On match, use seekp to move back one record and overwrite with new data.

Write a program to read and write the information of 10 students in a file. Also modify the student information according to the given roll number.

The program (1) writes 10 student records to a binary file, (2) displays them, and (3) modifies a record chosen by roll number using seekp().

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

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

int main() {
    Student s;
    fstream f("student.dat", ios::out | ios::binary);
    for (int i = 0; i < 10; i++) {            // write 10 students
        s.getData();
        f.write((char*)&s, sizeof(s));
    }
    f.close();

    f.open("student.dat", ios::in | ios::binary);   // read and show
    while (f.read((char*)&s, sizeof(s)))
        s.display();
    f.close();

    int r;
    bool found = false;
    cout << "Enter roll number to modify: ";
    cin >> r;
    f.open("student.dat", ios::in | ios::out | ios::binary);
    while (f.read((char*)&s, sizeof(s))) {
        if (s.getRoll() == r) {
            cout << "Enter new data:\n";
            s.getData();
            f.seekp(-(long)sizeof(s), ios::cur);   // back one record
            f.write((char*)&s, sizeof(s));
            found = true;
            break;
        }
    }
    f.close();
    if (!found) cout << "Roll number not found\n";

    f.open("student.dat", ios::in | ios::binary);   // show updated file
    while (f.read((char*)&s, sizeof(s)))
        s.display();
    f.close();
    return 0;
}

✓ Answer checked by Claude Opus 5.5 (high effort)

All Object Oriented Programming chapter 8 questions →