c++fstream

how to correctly write vector to binary file in c++?


first sorry for my bad english. i am just joined this forum and search for how to correctly write vector to binary file. i just got from this forum an answer like this(i have modified it a little):

#include <iostream>
#include <string.h>
#include <vector>
#include <fstream>

using namespace std;

class Student
{
public:
char m_name[30];
int m_score;

public:
Student()
{

}
Student(const char name[], const int &score)
:m_score(score)
{
    strcpy(m_name, name);
}
void print() const
{
    cout.setf(ios::left);
    cout.width(20);
    cout << m_name << " " << m_score << endl;
}
};


int main()
{
    vector<Student> student;
    student.push_back(Student("Alex",19));
    student.push_back(Student("Maria",20));
    student.push_back(Student("muhamed",20));
    student.push_back(Student("Jeniffer",20));
    student.push_back(Student("Alex",20));
    student.push_back(Student("Maria",21));

    ofstream fout("data.dat", ios::out | ios::binary);
    fout.write((char*) &student, sizeof(student));
    fout.close();

    vector<Student> student2;

    ifstream fin("data.dat", ios::in | ios::binary);
    fin.seekg(0, ifstream::end);
    int size = fin.tellg() / sizeof (student2);
    student2.resize(size);
    fin.seekg(0, ifstream::beg);
    fin.read((char*)&student2, sizeof(student2));
    vector<Student>::const_iterator itr = student2.begin();
    while(itr != student2.end())
    {
            itr->print();
            ++itr;
    }
    fin.close();
    return 0;
}

but when i run it. on my linux mint i got this result:

Alex                 19
Maria                20
muhamed              20
Jeniffer             20
Alex                 20
Maria                21
*** glibc detected *** ./from vector to binary: corrupted double-linked list: 0x0000000000633030 ***

i am new to c++. some one please help me, been stuck in this problem last 2 weeks. thanks in advance for the answer.


Solution

  • You are writing to file the vector structure, not its data buffer. Try change writing procedure to:

    ofstream fout("data.dat", ios::binary);
    fout.write((char*)&student[0], student.size() * sizeof(Student));
    fout.close();
    

    And instead of calculation size of vector from file size, it's better write vector size (number of objects) before. In the case you can write to the same file other data.

    size_t size = student.size();
    fout.write((char*)&size, sizeof(size));