c++

C++中buffer的序列化与反序列化方法是什么

小樊
86
2024-08-07 20:04:26
栏目: 编程语言

在C++中,可以使用std::ofstream和std::ifstream来进行buffer的序列化和反序列化。

序列化:

#include <iostream>
#include <fstream>
#include <vector>

void serializeBuffer(const std::vector<char>& buffer, const std::string& filename) {
    std::ofstream out(filename, std::ios::binary);
    if(out.is_open()) {
        out.write(buffer.data(), buffer.size());
        out.close();
    } else {
        std::cout << "Failed to open file for writing." << std::endl;
    }
}

int main() {
    std::vector<char> buffer = {'a', 'b', 'c', 'd', 'e'};
    serializeBuffer(buffer, "serialized_buffer.bin");

    return 0;
}

反序列化:

#include <iostream>
#include <fstream>
#include <vector>

std::vector<char> deserializeBuffer(const std::string& filename) {
    std::ifstream in(filename, std::ios::binary);
    std::vector<char> buffer;

    if(in.is_open()) {
        in.seekg(0, std::ios::end);
        buffer.resize(in.tellg());
        in.seekg(0, std::ios::beg);

        in.read(buffer.data(), buffer.size());
        in.close();
    } else {
        std::cout << "Failed to open file for reading." << std::endl;
    }

    return buffer;
}

int main() {
    std::string filename = "serialized_buffer.bin";
    std::vector<char> deserializedBuffer = deserializeBuffer(filename);

    for(char c : deserializedBuffer) {
        std::cout << c << " ";
    }
    std::cout << std::endl;

    return 0;
}

这样就可以将buffer序列化到文件中,并从文件中反序列化出来。

0
看了该问题的人还看了