【问题标题】:Parse in text file for Google Protocol Buffer为 Google Protocol Buffer 解析文本文件
【发布时间】:2012-06-06 05:02:24
【问题描述】:

根据示例代码https://developers.google.com/protocol-buffers/docs/cpptutorial,他们展示了如何解析二进制格式的原始文件。使用

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 文件?

【问题讨论】:

    标签: c++ input io protocol-buffers


    【解决方案1】:

    好的,我明白了。将文本 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;
    }
    

    当我在终端执行它时,我的程序将 proto buff 的输入文件作为第一个参数。例如./myProg inputFile.txt

    希望对有相同问题的人有所帮助

    【讨论】:

    • 文本文件的布局应该是什么?假设您有 2 个整数和 1 个字符串。您是否使用花括号来分隔每个条目?
    【解决方案2】:

    读取文本格式的 proto 文件需要做什么?

    使用TextFormat::Parse。我对 C++ 了解的不够多,无法为您提供完整的示例代码,但 TextFormat 是您应该寻找的地方。

    【讨论】:

      【解决方案3】:

      只是总结要点:

      #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 上的 g++ 4.9.2 上使用 protobuf-3.0.0-beta-1 检查。

      【讨论】:

        猜你喜欢
        • 2023-03-16
        • 1970-01-01
        • 2015-03-16
        • 1970-01-01
        • 2011-11-20
        • 1970-01-01
        • 2012-11-08
        • 2015-10-31
        • 2011-11-17
        相关资源
        最近更新 更多