File handling in C++ gives .exe stopped working error -
i have basic file handling code of reading file named"student.dat" using visual studio.
the output reads file , displays result in console visual studio pops dialog as
code:
#include<iostream> #include<fstream> #include<conio.h> #include<string> using namespace std; class student { int admno; // char name[20]; string name; public: void getdata() { cout<<"\n\nenter name of student "; //gets(name); cin>>name; getch(); cout<<"\nenter admission no. "; cin>>admno; // getch(); } void showdata() { cout<<"\nadmission no. : "<<admno; cout<<"\nstudent name : "; cout<<name; //puts(name); } int retadmno() { return admno; } }; int main() { student obj; ifstream fp1; fp1.open("student.dat",ios::binary); while(fp1.read((char*)&obj,sizeof(obj))) { obj.showdata(); } fp1.close(); return 0; }
you try store/load object file, invalid.
while(fp1.read((char*)&obj,sizeof(obj)))
objects may contain references memory (std::string e.g.) invalid after loading. have provide serialization objects or use plain structs without pointers or references store data. e.g.:
struct { int admno; char[20] name; }
if need strings variable length, may use string store:
struct { int admno; size_t name_index; } std::vector<std::string> names;
to store, iterate on names , save length , .c_str
of each std::string
. read, other way around , read length n, read n bytes buffer , construct std::string
out of buffer.
you might have @ http://www.boost.org/doc/libs/1_55_0/libs/serialization/doc/index.html
Comments
Post a Comment