Parse in text file for Google Protocol Buffer

非 Y 不嫁゛ 提交于 2019-12-21 04:03:07

问题


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;
  }
}

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?


回答1:


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;
}

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




回答2:


What do I need to do to read in a proto file in text format?

Use TextFormat::Parse. I don't know enough C++ to give you full sample code, but TextFormat is where you should be looking.




回答3:


Just to summarize the essentials:

#include <google/protobuf/text_format.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
#include <fcntl.h>
using namespace google::protobuf;

(...)

MyMessage parsed;
int fd = open(textFileName, O_RDONLY);
io::FileInputStream fstream(fd);
TextFormat::Parse(&fstream, &parsed);

Checked with protobuf-3.0.0-beta-1 on g++ 4.9.2 on Linux.



来源:https://stackoverflow.com/questions/10842066/parse-in-text-file-for-google-protocol-buffer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!