【发布时间】:2016-01-20 03:02:47
【问题描述】:
我用 c++ 中的错误字段模拟了一个文本格式的文件解析。
我的简单测试 .proto 文件:
$ cat settings.proto
package settings;
message Settings {
optional int32 param1 = 1;
optional string param2 = 2;
optional bytes param3 = 3;
}
我的文本格式文件:
$ cat settings.txt
param1: 123
param: "some string"
param3: "another string"
我正在使用 google::protobuf::TextFormat::Parser: 解析文件:
#include <iostream>
#include <fcntl.h>
#include <unistd.h>
#include <fstream>
#include <google/protobuf/text_format.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
#include <settings.pb.h>
using namespace std;
int main( int argc, char* argv[] )
{
GOOGLE_PROTOBUF_VERIFY_VERSION;
settings::Settings settings;
int fd = open( argv[1], O_RDONLY );
if( fd < 0 )
{
cerr << " Error opening the file " << endl;
return false;
}
google::protobuf::io::finputStream finput( fd );
finput.SetCloseOnDelete( true );
google::protobuf::TextFormat::Parser parser;
parser.AllowPartialMessage( true );
if ( !parser.Parce( &finput, &settings ) )
{
cerr << "Failed to parse file!" << endl;
}
cout << settings.DebugString() << endl;
google::protobuf::ShutdownProtobufLibrary();
std::cout << "Exit" << std::endl;
return true;
}
我为解析器将 AllowPartialMessage 设置为 true。所有字段都是可选的。 但目前 Parse 在第一个错误字段后停止解析。并且解析后“设置”只包含一个第一个字段。
有没有办法通知失败并继续解析另一个正确的字段?
【问题讨论】:
-
你不应该尝试它。垃圾进,垃圾出。
标签: c++ parsing protocol-buffers