//示意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;
}