简单的结构体序列化

#include <iostream>
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <string.h>
class A{
public:
    int double_data;
    char name[10] = "hello";
};

int main(int argc ,char * argv[]) {
    A *before = new A();
    before->double_data = 100;

    FILE *open_file = fopen(argv[1], "a+");
    if (fwrite(&before, sizeof(A), 1, open_file)!= 1) {
        printf("fwrite error\n");
    }
    A *after = new A();
    printf("dump ok\n");
    fclose(open_file);

    open_file = fopen(argv[1], "r");
    fread(&after, sizeof(A), 1, open_file);
    for (int i = 2; i < 6;++i) {
        printf("%d", after->double_data);
    }
    printf("fread ok\n");
    return 0;
}

缺点在于不能跨系统跨语言
把字节读出来二进制表示即可实现跨语言跨平台

结构体序列化和反序列化是将结构体数据转换为字节流,以便在网络传输或存储中使用,然后再将字节流还原为原始结构体数据的过程。 在C++中,可以通过以下几种方式实现结构体序列化和反序列化: 1. 使用二进制流进行序列化和反序列化:可以使用std::ofstream和std::ifstream类来将结构体数据写入文件或从文件读取结构体数据。例如: ```cpp struct MyStruct { int a; float b; char c; }; void serialize(const MyStruct& data, const std::string& filename) { std::ofstream file(filename, std::ios::binary); file.write(reinterpret_cast<const char*>(&data), sizeof(MyStruct)); file.close(); } void deserialize(MyStruct& data, const std::string& filename) { std::ifstream file(filename, std::ios::binary); file.read(reinterpret_cast<char*>(&data), sizeof(MyStruct)); file.close(); } ``` 2. 使用JSON进行序列化和反序列化:可以使用第三方库(如RapidJSON、nlohmann/json等)将结构体数据转换为JSON格式的字符串,然后再将JSON字符串转换回结构体数据。例如: ```cpp #include <iostream> #include <string> #include <nlohmann/json.hpp> struct MyStruct { int a; float b; char c; }; void serialize(const MyStruct& data, const std::string& filename) { nlohmann::json json_data; json_data["a"] = data.a; json_data["b"] = data.b; json_data["c"] = data.c; std::ofstream file(filename); file << json_data.dump(4); // 4为缩进级别 file.close(); } void deserialize(MyStruct& data, const std::string& filename) { std::ifstream file(filename); nlohmann::json json_data; file >> json_data; file.close(); data.a = json_data["a"]; data.b = json_data["b"]; data.c = json_data["c"]; } int main() { MyStruct original_data {42, 3.14f, 'A'}; serialize(original_data, "data.json"); MyStruct restored_data; deserialize(restored_data, "data.json"); std::cout << "Restored data: a = " << restored_data.a << ", b = " << restored_data.b << ", c = " << restored_data.c << std::endl; return 0; } ``` 以上是两种常见的结构体序列化和反序列化的方式,具体选择哪种方式取决于你的需求和场景。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值