Laxmi Kadariya
Laxmi Kadariya

Reputation: 1103

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 the file and displays the result in console but visual studio pops up the dialog as

enter image description here

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 The Name of The Student ";
                     //gets(name);
                     cin>>name;
                     getch();
                     cout<<"\nEnter The 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;
}

Upvotes: 1

Views: 172

Answers (3)

urzeit
urzeit

Reputation: 2909

You try to store/load an object to a file, which is invalid.

while(fp1.read((char*)&obj,sizeof(obj)))

Objects may contain references to memory (std::string e.g.) that are invalid after loading. You have to provide serialization for your objects or use plain structs without pointers or references to store your data. E.g.:

struct {
    int      admno;
    char[20] name;
}

If you need strings with variable length, you may use a string store:

struct {
    int     admno;
    size_t  name_index;
}

std::vector<std::string> names;

To store, iterate over your names and save length and .c_str of each std::string. To read, do it the other way around and read length into n, read n bytes into a buffer and construct a std::string out of the buffer.

You might have a look at http://www.boost.org/doc/libs/1_55_0/libs/serialization/doc/index.html

Upvotes: 2

Ivan
Ivan

Reputation: 2057

You are allowed to load raw data only to some POD objects. This line is an error:

fp1.read( (char*)&obj,sizeof(obj) );

because student contains std::string. std::string contains a pointer to a memory block which becomes invalid and totally useless after the object is destroyed. It means the data you load to std::string is just a garbage.

I'd think about object serialization. Boost serialization is a good way to start.

Upvotes: 3

Eamonn McEvoy
Eamonn McEvoy

Reputation: 8986

You never call GetData so admno is not instantiated in ShowData

Upvotes: 0

Related Questions