c++ - 在 C++ 中向/从二进制文件写入/读取结构

标签 c++ serialization binary structure ifstream

我正在构建一个数据库工具,我想做的就是将一个结构写入二进制文件,然后再次读入。以下是我在网上能找到的最接近的做法,但它存在重大问题:

#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 行),其次,更改 input 写入后的结构(正如我在示例中所做的那样)改变了假定的读取结构。我想正在发生的事情是不知何故“数据”和“inData”是同一件事(这可以解释崩溃,因为它会尝试从内存中删除相同的东西两次)。任何人都可以让它工作吗?我已经尝试了所有我能想到的方法。

最佳答案

问题是您的结构是动态的(由于 vector )。这总是会使事情复杂化,因为您实际上是在存储一个 char *。 vector 是一个复杂的数据结构。您不能只是将其屏蔽为 char * 并期望它代表元素。所以你甚至没有存储你需要的东西。 我建议您将 vector 更改为类似 int grades[NO_OF_SUBJECTS] 的内容。那应该可以正常工作。

关于c++ - 在 C++ 中向/从二进制文件写入/读取结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10485182/

相关文章:

c++ - 获取特定进程的线程句柄/id

c++ - CRT 和 WIN32 API

c - 海湾合作委员会错误 : Invalid operands to binary +

适用于 App Store 的 iPhone 二进制文件

c# - c++/c#传销是怎么做出来的?

c++ - 自动转换为指针而不自动转换为 bool(-like) 可能吗?

java - Jackson:使用过滤时空嵌套实体

php - JQuery Datatables序列化数据到mysql数据库

java - 更新类的serialVersionUID理解

Python:向用户询问列表变量