gpt4 book ai didi

c++ - 解析 Google Protocol Buffer 的文本文件

转载 作者:可可西里 更新时间:2023-11-01 16:29:21 28 4
gpt4 key购买 nike

根据示例代码https://developers.google.com/protocol-buffers/docs/cpptutorial ,它们展示了如何在二进制格式的原型(prototype)文件中进行解析。使用

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 文件需要做什么?

最佳答案

好的,我明白了。将文本原型(prototype)文件读入对象....

#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

希望对遇到同样问题的人有所帮助

关于c++ - 解析 Google Protocol Buffer 的文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10842066/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com