0

I made a program that writes a structure into a binary file, and then reads that binary file into a different variable. Writing into file and reading from it works fine, however the program crashes on exit.

I tried using the same variable for reading which works, but is not the solution I'm looking for. I want to know why the program crashes when I read structure from binary file into a different variable.

Here's the code:

#include <iostream>
#include <fstream>
#include <ctime>
#include <stdlib.h>

using namespace std;

struct t_student{
    string name;
    string lastname;
    int mark;
};

int main(){
    t_student student[30], student_read[30];
    int n, i;
    srand(time(0));

    fstream dat("student.dat", ios::in | ios::out | ios::binary | ios::trunc);

    cout << "Input number of students (up to 30): ";
    cin >> n;
    if(n > 30) n = 30;
    cout << endl;

    cin.ignore();
    for(i = 0; i < n; i++){
        cout << "Input first name: ";
        getline(cin, student[i].name);

        cout << "Input last name: ";
        getline(cin, student[i].lastname);

        student[i].mark = rand()%5+1;

        cout << endl;

        dat.write((char *) &student[i], sizeof(student[i]));
    }

    dat.clear();
    dat.seekg(0);
    i = 0;

    while(!dat.eof()){
        dat.read((char *) &student_read[i], sizeof(student_read[i]));
        if(dat.eof()) break;
        cout << endl << student_read[i].name << " " << student_read[i].lastname << "  -  " << student_read[i].mark;
        i++;
    }
    dat.close();

    cin.get();
    //exit(0);
}

As you might notice, I also added exit(0) function, which prevents the program from crashing, but I want to know why the program crashes in the first place.

Thanks for your help.

Izak
  • 307
  • 5
  • 12
  • 3
    `dat.write((char *) &student[i], sizeof(student[i]));` You can't [serialize](http://en.wikipedia.org/wiki/Serialization) complex objects (i.e. `std::string`) like that. They have internal pointers that need serializing. Doing so will likely lead to undefined behavior if you try to deserialize them (like you later do). – Cornstalks Dec 21 '14 at 20:25
  • 3
    I think, your reading/writing code is incorrect. In C++ you just can't read/write struct with string into/from file, without some form of serialization. You can try Boost, e.g. Boost serialization www.boost.org/doc/libs/release/libs/serialization/ – osgx Dec 21 '14 at 20:26
  • Thank you both. Apparently our proffesor in school has been teaching us wrong. I will sure tell him that he is mistaken. – Izak Dec 21 '14 at 20:46

0 Answers0