我正在构建一个数据库工具,我想做的就是将一个结构写入二进制文件,然后再次读取它。以下是我在网上能找到的最接近的方法,但它存在重大问题:
#include <fstream>
#include <iostream>
#include <vector>
#include <string.h>
using namespace std;
typedef struct student
{
char name[10];
int age;
vector<int> grades;
}student_t;
int main()
{
student_t apprentice[3];
strcpy(apprentice[0].name, "john");
apprentice[0].age = 21;
apprentice[0].grades.push_back(1);
apprentice[0].grades.push_back(3);
apprentice[0].grades.push_back(5);
strcpy(apprentice[1].name, "jerry");
apprentice[1].age = 22;
apprentice[1].grades.push_back(2);
apprentice[1].grades.push_back(4);
apprentice[1].grades.push_back(6);
strcpy(apprentice[2].name, "jimmy");
apprentice[2].age = 23;
apprentice[2].grades.push_back(8);
apprentice[2].grades.push_back(9);
apprentice[2].grades.push_back(10);
// Serializing struct to student.data
ofstream output_file("students.data", ios::binary);
output_file.write((char*)&apprentice, sizeof(apprentice));
output_file.close();
// Reading from it
ifstream input_file("students.data", ios::binary);
student_t master[3];
input_file.read((char*)&master, sizeof(master));
apprentice[0].grades[0]=100; // ALTERING THE INPUT STRUCTURE AFTER WRITE
for (size_t idx = 0; idx < 3; idx++)
{
// If you wanted to search for specific records,
// you should do it here! if (idx == 2) ...
cout << "Record #" << idx << endl;
cout << "Name: " << master[idx].name << endl;
cout << "Age: " << master[idx].age << endl;
cout << "Grades: " << endl;
for (size_t i = 0; i < master[idx].grades.size(); i++)
cout << master[idx].grades[i] << " ";
cout << endl << endl;
}
return 0;
}
这似乎是在写入文件,将其读回然后打印到屏幕上,但不幸的是:首先,程序在尝试关闭时因调试断言失败(dbgdel.cpp 第 52 行)而崩溃,其次,在写入后更改输入结构(正如我在示例中所做的那样)改变了所谓的读取结构。我猜正在发生的事情是不知何故“数据”和“inData”是同一件事(这可以解释崩溃,因为它会尝试从内存中删除同一件事两次)。谁能得到这个工作?我已经尝试了我能想到的一切。