首先对不起我的英语不好。我刚加入这个论坛并搜索如何正确地将向量写入二进制文件。我刚从这个论坛得到一个这样的答案(我已经修改了一点):
#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;
}
但是当我运行它时。在我的 linux mint 上,我得到了这个结果:
Alex 19 Maria 20 muhamed 20 Jeniffer 20 Alex 20 Maria 21 *** glibc detected *** ./from vector to binary: corrupted double-linked list: 0x0000000000633030 ***
我是 C++ 新手。有人请帮助我,过去两周一直陷入这个问题。提前感谢您的回答。
原文由 dchochan 发布,翻译遵循 CC BY-SA 4.0 许可协议
您正在写入文件矢量结构,而不是其数据缓冲区。尝试将写入程序更改为:
而不是从文件大小计算向量的大小,最好先写向量大小(对象数)。在这种情况下,您可以将其他数据写入同一文件。