使用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);

 

posted on 2014-09-29 11:28  落叶歸根  阅读(1744)  评论(0编辑  收藏  举报

导航