解析Google协议缓冲区的文本文件 [英] Parse in text file for Google Protocol Buffer
问题描述
根据示例代码 https://developers.google.com/protocol-buffers/docs/cpptutorial ,它们展示了如何解析二进制格式的proto文件。使用
According to the example code https://developers.google.com/protocol-buffers/docs/cpptutorial, they show how to parse in a proto file that is in binary format. using
tutorial::AddressBook address_book;
{
// Read the existing address book.
fstream input(argv[1], ios::in | ios::binary);
if (!address_book.ParseFromIstream(&input)) {
cerr << "Failed to parse address book." << endl;
return -1;
}
}
我尝试删除 ios :: binary
用于我的文本格式的输入文件,但在读取文件时仍然失败。我需要做什么来读取文本格式的原型文件?
I tried removing the ios::binary
for my input file that is in text format, but that still fails at reading in the file. What do I need to do to read in a proto file in text format?
推荐答案
好吧,我弄明白了。将文本原型文件读入对象....
Alright, I got this figured out. To read in a text proto file into an object....
#include <iostream>
#include <fcntl.h>
#include <fstream>
#include <google/protobuf/text_format.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
#include "YourProtoFile.pb.h"
using namespace std;
int main(int argc, char* argv[])
{
// Verify that the version of the library that we linked against is
// compatible with the version of the headers we compiled against.
GOOGLE_PROTOBUF_VERIFY_VERSION;
Tasking *tasking = new Tasking(); //My protobuf object
bool retValue = false;
int fileDescriptor = open(argv[1], O_RDONLY);
if( fileDescriptor < 0 )
{
std::cerr << " Error opening the file " << std::endl;
return false;
}
google::protobuf::io::FileInputStream fileInput(fileDescriptor);
fileInput.SetCloseOnDelete( true );
if (!google::protobuf::TextFormat::Parse(&fileInput, tasking))
{
cerr << std::endl << "Failed to parse file!" << endl;
return -1;
}
else
{
retValue = true;
cerr << "Read Input File - " << argv[1] << endl;
}
cerr << "Id -" << tasking->taskid() << endl;
}
我的程序将proto buff的输入文件作为第一个参数我在终端执行它。例如 ./ myProg inputFile.txt
My program takes in the input file for the proto buff as the first parameter when i execute it at the terminal. For example ./myProg inputFile.txt
希望这可以帮助任何有相同问题的人
Hope this helps anyone with the same question
这篇关于解析Google协议缓冲区的文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!