写数据
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 
 | #include "msg.pb.h"#include <fstream>
 #include <iostream>
 using namespace std;
 
 int main(void)
 {
 
 lm::helloworld msg1;
 msg1.set_id(101);
 msg1.set_str("hello");
 fstream output("./log", ios::out | ios::trunc | ios::binary);
 
 if (!msg1.SerializeToOstream(&output)) {
 cerr << "Failed to write msg." << endl;
 return -1;
 }
 return 0;
 }
 
 | 
 读数据
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 
 | #include "msg.pb.h"#include <fstream>
 #include <iostream>
 using namespace std;
 
 void ListMsg(const lm::helloworld & msg) {
 cout << msg.id() << endl;
 cout << msg.str() << endl;
 }
 
 int main(int argc, char* argv[]) {
 
 lm::helloworld msg1;
 
 {
 fstream input("./log", ios::in | ios::binary);
 if (!msg1.ParseFromIstream(&input)) {
 cerr << "Failed to parse address book." << endl;
 return -1;
 }
 }
 
 ListMsg(msg1);
 }
 
 | 
 编译
Makefile内容为
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 
 | all: write read
 clean:
 @rm -f write read msg.*.cc msg.*.h *.o  log
 
 write: msg.pb.cc write.cc
 g++ -std=c++11  msg.pb.cc write.cc -o write  `pkg-config --cflags --libs protobuf`
 
 read: msg.pb.cc read.cc
 g++ -std=c++11  msg.pb.cc read.cc -o read  `pkg-config --cflags --libs protobuf`
 
 msg.pb.cc msg.pb.h :msg.proto
 protoc --cpp_out=. ./msg.proto
 
 | 
 结果
执行编译操作,自动生成代码,编译程序。
先运行写,然后读取之前写入的101和hello数据。