在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序列化到文件中,并從文件中反序列化出來。