C++实现protobuf

一、配置protobuf开发环境
二、创建 .proto 文件,定义数据结构

//message.proto
syntax = "proto2";
package Message;
message MessageTest{
      required int64  dateTime = 1;
      required string hostName = 2;
      required string ip = 3;
      required string info = 4;
  // 字段规则:required -> 字段只能也必须出现 1 次
  // 字段规则:optional -> 字段可出现 0 次或1次
  // 字段规则:repeated -> 字段可出现任意多次(包括 0)
  // 类型:int32、int64、sint32、sint64、string、32-bit ....
  // 字段编号:0 ~ 536870911(除去 19000 到 19999 之间的数字)字段规则 类型 名称 = 字段编号;

三、编译.proto文件

protoc   --cpp_out=./ message.proto 

项目目录下会生成message.pb.hmessage.pb.cc文件

四、编写writer文件

//writer.cpp
#include "message.pb.h"
#include <fstream>
#include <iostream>
#include <sys/time.h>

using namespace std;
using namespace Message;

int main(void){
    MessageTest msg;

    struct timeval tv;
    struct timezone tz;
    gettimeofday(&tv,&tz);
    const long dateTime = tv.tv_sec;

    msg.set_datetime(dateTime);
    msg.set_hostname("dataNode-1000");
    msg.set_ip("192.168.0.128");
    msg.set_info("Everything is normal, I'm healthy");

    fstream output("message.db",ios::out|ios::trunc|ios::binary);
    if(!msg.SerializeToOstream(&output)){
        cerr << "save data error." << endl;
        return -1;
    }
    return 0;
}

编译

g++ -Wall -o writer writer.cpp message.pb.cc -lprotobuf -std=c++11

./writer

文件下生成:
在这里插入图片描述
五、编写reader文件

#include "message.pb.h"
#include <fstream>
#include <iostream>

using namespace std;
using namespace Message;

void traceMsg(const MessageTest &msg){
    cout << msg.datetime() << endl;
    cout << msg.hostname() << endl;
    cout << msg.ip() << endl;
    cout << msg.info() << endl;
}

int main(void){

    MessageTest msg;

    fstream input("message.db",ios::in|ios::binary);

    if(!msg.ParseFromIstream(&input)){
        cerr << "read data from file error." << endl;
        return -1;
    }
    traceMsg(msg);
    return 0;
}
g++ -Wall -o reader read.cpp message.pb.cc -lprotobuf -std=c++11

./reader
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值