Skip to main content

Student records file with CRN search

Short answer

Write N student records to stud.dat in binary mode. To search by CRN, read records sequentially until a matching CRN is found and display details; if not found, show a message.

Create class student to store Name, Age and CRN of students. Write a program to write records of N numbers of students into the file. And your program should search complete information of students from file according to CRN entered by user and display it.

Assumption: records are saved in the binary file stud.dat; the search is a sequential read comparing CRN.

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

class Student {
    char name[30];
    int age;
    long crn;
public:
    void getData() {
        cout << "Name, Age, CRN: ";
        cin >> name >> age >> crn;
    }
    void display() {
        cout << "Name: " << name << "\nAge: " << age
             << "\nCRN: " << crn << endl;
    }
    long getCrn() { return crn; }
};

int main() {
    Student s;
    int n;
    cout << "Number of students: ";
    cin >> n;

    ofstream fout("stud.dat", ios::binary);
    for (int i = 0; i < n; i++) {
        s.getData();
        fout.write((char*)&s, sizeof(s));
    }
    fout.close();

    long key;
    cout << "Enter CRN to search: ";
    cin >> key;

    ifstream fin("stud.dat", ios::binary);
    bool found = false;
    while (fin.read((char*)&s, sizeof(s))) {
        if (s.getCrn() == key) {
            s.display();
            found = true;
            break;
        }
    }
    fin.close();
    if (!found) cout << "No student with CRN " << key << endl;
    return 0;
}

✓ Answer checked by Claude Opus 5.5 (high effort)

All Object Oriented Programming chapter 8 questions →