对于结构体或者类对象的序列化反序列化

#include <iostream>
#include <fstream>

struct MyStruct {
    
    
    int myInt;
    std::string myString;
};

// 序列化函数的模板
template<typename T>
void Serialize(const T& obj, const std::string& filename) {
    
    
    std::ofstream file(filename, std::ios::binary);
    if (file.is_open()) {
    
    
        file.write((char*)&obj, sizeof(obj));
        file.close();
        std::cout << "Serialization complete." << std::endl;
    }
    else {
    
    
        std::cerr << "Failed to open file for writing." << std::endl;
    }
}

// 反序列化函数的模板
template<typename T>
T Deserialize(const std::string& filename) {
    
    
    T obj;
    std::ifstream file(filename, std::ios::binary);
    if (file.is_open()) {
    
    
        file.read((char*)&obj, sizeof(obj));
        file.close();
        std::cout << "Deserialization complete." << std::endl;
    }
    else {
    
    
        std::cerr << "Failed to open file for reading." << std::endl;
    }
    return obj;
}

int main() {
    
    
    MyStruct originalObj;
    originalObj.myInt = 42;
    originalObj.myString = "Hello, World!";

    // 序列化对象
    Serialize(originalObj, "data.bin");

    // 反序列化对象
    MyStruct restoredObj = Deserialize<MyStruct>("data.bin");

    // 打印反序列化的对象
    std::cout << "myInt: " << restoredObj.myInt << std::endl;
    std::cout << "myString: " << restoredObj.myString << std::endl;

    return 0;
}

猜你喜欢

转载自blog.csdn.net/neuzhangno/article/details/132411726