使用protobuf编写配置文件以及读写

.proto文件示例

message Configure
{
    required string host = 1;
    required uint32 port = 2;
}

 

写配置文件

Configure config;

config.set_host("127.0.0.1");
config.set_port(8080);


string
contect; google::protobuf::TextFormat::PrintToString(config, & contect);

ofstream fout;

fout.open("config.cfg", ios::out| ios_base::ate);

if (!fout.is_open())
{
    fprintf(stderr, "open config.cfg fail\n");
    return -1;
}

fout << contect <<endl;

fout.flush();

fout.close();

读配置文件

int fd = open("config.cfg", O_RDONLY);

if (fd < 0)
{
    printf("open config.cfg failure:%s \n",strerror(errno));
    return false;
}

google::protobuf::io::FileInputStream fileInput(fd);

fileInput.SetCloseOnDelete(true);

google::protobuf::TextFormat::Parse(&fileInput, &config);

 

转载于:https://www.cnblogs.com/evan-cai/p/3999845.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值