【demo】利用protobuf读取配置文件

说明

这是一个利用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
  }
}

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值