背景
protobuf 是一种跨平台的序列化结构数据的方法,可用于网络数据传输及存储。
二进制数据读写
①.概述
protobuf 一般用于结构数据的序列化后进行网络传输。
②.数据序列化
使用成员函数 SerializeAsString 进行序列化操作,使用 string 类型保存返回的二进制数据。
protoTest::DemoMsg msg;
msg.set_id(1);
msg.set_name("Zhangsan");
string s = msg.SerializeAsString();
③.数据反序列化
使用成员函数 ParseFromString 进行反序列化操作。
protoTest::DemoMsg msg;
msg.set_id(1);
msg.set_name("Zhangsan");
string s = msg.SerializeAsString();
msg.Clear();
msg.ParseFromString(s);
cout << "id " << msg.id() << endl;
cout << "name " << msg.name() << endl;
文本数据读写
①.概述
protobuf 也可以把结构数据序列化为可识别的文本数据。
②.数据序列化
使用 TextFormat 类可以把结构数据转换为文本字符串。
protoTest::DemoMsg msg;
msg.set_id(1);
msg.set_name("Zhangsan");
string s;
TextFormat::PrintToString(msg, &s);
cout << s << endl;
③.数据反序列化
protoTest::DemoMsg msg;
msg.set_id(1);
msg.set_name("Zhangsan");
string s;
TextFormat::PrintToString(msg, &s);
msg.Clear();
TextFormat::ParseFromString(s, &msg);
cout << "id " << msg.id() << endl;
cout << "name " << msg.name() << endl;
二进制文件读写
①.概述
protobuf 也可以用于结构数据的存储。
②.数据序列化
protoTest::DemoMsg msg;
msg.set_id(1);
msg.set_name("Zhangsan");
ofstream file("demo", ios::binary);
msg.SerializeToOstream(&file);
file.clear();
③.数据反序列化
protoTest::DemoMsg msg;
ifstream in_file("demo", ios::binary);
msg.ParseFromIstream(&in_file);
cout << "id " << msg.id() << endl;
cout << "name " << msg.name() << endl;
文本文件读写
①.概述
protobuf 也可以把结构数据以文本形式保存到文件,可以当作系统的配置文件使用。
②.数据序列化
使用 TextFormat 类 的 Print 方法可以把结构数据转换为文本字符串并保存到文件。
protoTest::DemoMsg msg;
msg.set_id(1);
msg.set_name("Zhangsan");
int fd = open("demo", O_BINARY | O_WRONLY | O_CREAT);
FileOutputStream *output = new FileOutputStream(fd);
TextFormat::Print(msg, output);
delete output; output = nullptr;
close(fd);
③.数据反序列化
使用 TextFormat 类 的 Parse方法可以从文本文件中读取数据到结构。
protoTest::DemoMsg msg;
int fd = open("demo", O_RDONLY);
FileInputStream *input = new FileInputStream(fd);
TextFormat::Parse(input,&msg);
delete input; input = nullptr;
close(fd);
cout << "id " << msg.id() << endl;
cout << "name " << msg.name() << endl;