一个示例序列化程序的 C++ 代码


#include <fstream>
#include <string>

using namespace std;

// 定义一个结构体,用于存储要序列化的数据
struct Data {
    string name;
    int age;
    double height;
};

// 定义一个函数,用于将结构体序列化为二进制数据
void serialize(const Data& data, ostream& stream) {
    stream.write(data.name.c_str(), data.name.size());
    stream.write(reinterpret_cast<const char*>(&data.age), sizeof(data.age));
    stream.write(reinterpret_cast<const char*>(&data.height), sizeof(data.height));
}

// 定义一个函数,用于将二进制数据反序列化为结构体
void deserialize(istream& stream, Data& data) {
    getline(stream, data.name, '\0');
    stream.read(reinterpret_cast<char*>(&data.age), sizeof(data.age));
    stream.read(reinterpret_cast<char*>(&data.height), sizeof(data.height));
}

int main() {
    // 定义一个结构体,存储要序列化的数据
    Data data = {"John Doe", 35, 1.75};

    // 序列化数据并将其写入文件
    ofstream file("data.bin", ios::binary);
    serialize(data, file);
    file.close();

    // 从文件中读取二进制数据并反序列化
    Data readData;
    ifstream file("data.bin", ios::binary);
    deserialize(file, readData);
    file.close();

    // 输出反序列化后的数据
    cout << "Name: " << readData.name << endl;
    cout << "Age: " << readData.age << endl;
    cout << "Height: " << readData.height << endl;

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值