11

コード例https://developers.google.com/protocol-buffers/docs/cpptutorialによると、バイナリ形式の proto ファイルを解析する方法を示しています。使用して

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たが、それでもファイルの読み込みに失敗します。proto ファイルをテキスト形式で読み込むにはどうすればよいですか?

4

3 に答える 3

17

わかりました、私はこれを理解しました。テキスト proto ファイルをオブジェクトに読み込むには....

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

私のプログラムは、ターミナルで実行すると、プロト バフの入力ファイルを最初のパラメーターとして受け取ります。例えば./myProg inputFile.txt

これが同じ質問を持つ人に役立つことを願っています

于 2012-06-01T01:16:07.160 に答える
3

proto ファイルをテキスト形式で読み込むにはどうすればよいですか?

TextFormat::Parseを使用します。完全なサンプル コードを提供するのに十分な C++ の知識はありませんTextFormatが、見るべきところです。

于 2012-05-31T22:25:03.360 に答える
1

要点を要約すると、次のようになります。

#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);

Linux ではprotobuf-3.0.0-beta-1onでチェック済み。g++ 4.9.2

于 2016-01-11T14:08:41.607 に答える