I am trying to read and write objects of my user defined structure to a binary file .My program writes my objects to the file then read it from the file but at the end it throws an exception 0x006787EA and my screen just become stuck and then I have to close visual studio forcefully. Please any one can spot out the mistake I am doing.
This is the code:
#include<iostream>
#include<fstream>
using namespace std;
struct Student {
int roll_no;
string name;
};
int main() {
ofstream wf("student.dat");
if (!wf) {
cout << "Cannot open file!" << endl;
return 1;
}
Student wstu[3];
wstu[0].roll_no = 1;
wstu[0].name = "mm";
wstu[1].roll_no = 2;
wstu[1].name = "Sasd";
wstu[2].roll_no = 3;
wstu[2].name = "sdasda";
for (int i = 0; i < 3; i++)
wf.write(reinterpret_cast<char*>(&wstu[i]), sizeof(Student));
wf.close();
if (!wf.good()) {
cout << "Error occurred at writing time!" << endl;
return 1;
}
ifstream rf("student.dat");
if (!rf) {
cout << "Cannot open file!" << endl;
return 1;
}
Student rstu[3];
for (int i = 0; i < 3; i++)
rf.read(reinterpret_cast<char*>(&rstu[i]), sizeof(Student));
rf.close();
if (!rf.good()) {
cout << "Error occurred at reading time!" << endl;
return 1;
}
cout << "Student's Details:" << endl;
for (int i = 0; i < 3; i++) {
cout << "Roll No: " << wstu[i].roll_no << endl;
cout << "Name: " << wstu[i].name << endl;
cout << endl;
}
return 0;
}