protobuf 存取数据

本文介绍了一种使用Proto文件进行数据序列化的方法,包括如何将数据序列化为字符串并保存到文件,以及如何从文件中读取字符串并解析为Proto结构。通过这种方式可以有效地存储和读取复杂的数据结构。
//示意proto文件
message B
{
	repeated posX;
}
message A
{
	repeated string name =1;
	required int id = 2;
	optional bool sex = 3;
	repeated B pos =4;//如此可以设计一个二维数组
}

读取proto到文件

bool Control::saveFile(const QString& filename) {
//把A类里面的信息存取到文件filename,使用proto的办法存
  A a;
 // serialize proto and write to file
  std::string path = filename.toStdString();
  ofstream pb_ofstream(path, ios::out);
  std::string buffer;
  a.SerializeToString(&buffer);
  qDebug() <<"存储的buffer size:"<< buffer.size();
  pb_ofstream << buffer;
  pb_ofstream.flush();
  pb_ofstream.close();
  return true;
}

读取文件信息到proto

bool Control::openSaveFile(const QString& filename) {
  // read binary data from file
  std::string path = filename.toStdString();
  ifstream pb_ifstream(path, ios::in);
  std::stringstream str_buffer;
  str_buffer << pb_ifstream.rdbuf();

  // parse string to proto structure
  //这个A类,就是在proto文件中定义的类,也就是message
  //使用ParseFromString就可以从文件中读取的buffer获得相关的信息
  //最后使用a就可以了,a里面有你之前存过的的任何信息
  auto a = A();
  a.ParseFromString(str_buffer.str());
  return true}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值