C++の間違ったフィールドで解析するテキスト形式のファイルをシミュレートします。テキスト形式のprotobufメッセージを解析するときに間違ったフィールドを無視する方法
ファイル.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"
を私はグーグル::いるProtobuf ::れるTextFormat ::パーサーでファイルを解析しています
#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は最初の間違ったフィールドの後に解析を停止します。また、解析後、「設定」には最初のフィールドが1つしかありません。
失敗したことを通知し、別の正しいフィールドを解析し続ける方法はありますか?
試してはいけません。ゴミ入れ、ゴミ出し。 – EJP