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

时间:2023-03-08 19:33:31
使用protobuf编写配置文件以及读写

.proto文件示例

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

写配置文件

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 -;
} fout << contect <<endl; fout.flush(); fout.close();

读配置文件

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

if (fd < )
{
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);