[英]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.