- 2073 Shrawan · 7 marks
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)
Related questions
- File stream; student binary file program · Object Oriented Programming, chapter 8
- Student records file with CRN search · Object Oriented Programming, chapter 8
- Student file displayed in descending marks order · Object Oriented Programming, chapter 8
- Protected specifier; student/test/result program · Object Oriented Programming, chapter 6
- Abstract Student class program · Object Oriented Programming, chapter 7
- Write and display 10 employees using file · Object Oriented Programming, chapter 8
- Binary file of 48 students; highest mark · Computer Programming, chapter 10
- Pass student array; display passed students · Computer Programming, chapter 7
- Store 48 students in file with append · Computer Programming, chapter 10
- 96 students record; pass marks · Computer Programming, chapter 10