说明:
当遇到未知字段或扩展名时,默认解析将失败。
如果我们不希望失败而是忽略,可以设置allow_unknown_field_和allow_unknown_extension_。
举例:
场景:
程序使用 google::protobuf::TextFormat::Parse
解析配置。
如果配置有新加字段,而程序又没有重新编译pb文件,那么会解析失败。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| int ReadCfgData(const std::string& file, google::protobuf::Message* message) { using google::protobuf::io::FileInputStream; int fd = open(file.c_str(), O_RDONLY); if (fd < 0) { LogErr("can't open file.{}", file); return -1; } FileInputStream input(fd); input.SetCloseOnDelete(true); if (file.substr(file.find_last_of(".")) == ".txt") { auto parse = google::protobuf::TextFormat::Parser(); parse.AllowUnknownField(true); if (!parse.Parse(&input, message)) { LogErr("txt file.{} parse error", file); return -2; } } else { if (!message->ParseFromZeroCopyStream(&input)) { LogErr("bytes file.{} parse error", file); return -3; } } return 0; }
|
注意:
设置忽略后将生成警告消息,并且可能会隐藏一些错误。