说明
这是一个利用protobuf读取配置文件的 demo。
利用protobuf读写二进制流的例子在网上有很多,但是读写配置文件我觉得也是一个很大的应用空间。
proto文件
ken@ubuntu:~/test/protobuf/test_pf$ cat addressbook.proto
syntax = "proto2";
package tutorial;
message Person {
required string name = 1;
required int32 id = 2;
optional string email = 3;
enum PhoneType {
MOBILE = 0;
HOME = 1;
WORK = 2;
}
message PhoneNumber {
required string number = 1;
optional PhoneType type = 2 [default = HOME];
}
repeated PhoneNumber phones = 4;
}
message AddressBook {
repeated Person people = 1;
}
生成命令
protoc -I=./ --cpp_out=./out ./addressbook.proto
cpp文件
ken@ubuntu:~/test/protobuf/test_pf$ cat src/pb_test.cpp
#include <iostream>
#include <fstream>
#include <string>
#include <unistd.h>
#include <fcntl.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
#include <google/protobuf/text_format.h>
#include "addressbook.pb.h"
using namespace std;
int main()
{
tutorial::AddressBook addrBook;
int fd = open("./cfg/pb.cfg", O_RDONLY);
google::protobuf::io::FileInputStream f_in(fd);
f_in.SetCloseOnDelete(true);
google::protobuf::TextFormat::Parse(&f_in, &addrBook);
addrBook.PrintDebugString();
return 0;
}
编译命令
g++ ./src/addressbook.pb.cc ./src/pb_test.cpp -o pb_test -I./include `pkg-config --cflags --libs protobuf`
配置文件
ken@ubuntu:~/test/protobuf/test_pf$ cat cfg/pb.cfg
people: {
name: "ken"
id: 1
email: "ken111@163.com"
phones: {
number: "13866666666"
type: MOBILE
}
}
执行结果
ken@ubuntu:~/test/protobuf/test_pf$ ./pb_test
people {
name: "ken"
id: 1
email: "ken111@163.com"
phones {
number: "13866666666"
type: MOBILE
}
}