[英]C++ protobuf: how to write multiple messages into file by “SerializeToOstream()”
我发现当我使用SerializeToOstream()时,只有最后一条消息被写入文件,之前的消息都被以后的调用覆盖。 像这样:
我是你的hello.proto:
message hello
{
required int32 f1=1;
required int32 f2=2;
optional int32 f3=3;
}
然后我编译并在一个cpp文件中使用它:
#include "hello.pb.h"
#include<fstream>
#include<iostream>
using namespace std;
int main()
{
fstream fo("./hello.data",ios::binary|ios::out);
hello p1,p2,p3;
p1.set_f1(1);
p1.set_f2(2);
p2.set_f1(3);
p2.set_f2(4);
p3.set_f1(5);
p3.set_f2(6);
p1.SerializeToOstream(&fo);
p2.SerializeToOstream(&fo);
p3.SerializeToOstream(&fo);
fo.close();
fstream fi("./hello.data",ios::binary|ios::in);
hello pi;
pi.ParseFromIstream(&fi);
cout<<pi.f1()<<pi.f2()<<endl;
return 0;
}
好吧,我发现只有“p3”被写入这个“hello.data”,p1和p2被覆盖了某种方式?
为什么protobuf只写最后一条消息? 我们通常使用protobuf来传递多条消息,对吧? 那么如何将多条消息写入一个文件? 如何纠正我的程序?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.