【问题标题】:How can I read a binary file into a protobuf that is of the type QString?如何将二进制文件读入 QString 类型的 protobuf?
【发布时间】:2020-04-03 08:43:09
【问题描述】:

所以我有一个二进制文件,它的名称作为const QString& filename 传递到我的函数中,我正在尝试将它读入ProtoBuf。我已经尝试了示例ParseFromArray(file.data(), file.size()),但它不起作用并且大小为1

这样做的正确方法是什么?谢谢!

这是我的相关代码sn-p:

bool open(const QString& filename)
{
    myProject::protobuf::Example _example;

    // need to copy contents from file to _example
}

【问题讨论】:

  • file是文件name还是文件contents
  • 请出示您的相关代码。看起来您需要先使用QFile 阅读所有内容,然后从返回的QByteArray 中获取data。但是,那将是推测性的。更新代码后,您会得到更好的响应。
  • file 是文件名
  • 我已经更新了代码,如果还有什么需要我提供的,请告诉我。谢谢!
  • @Kau:我已经根据您之前的评论更新了您的问题,即filefilename

标签: c++ qt file protocol-buffers


【解决方案1】:

您需要先使用QFile 打开文件,然后使用其继承的方法readAll() 读取其内容,该方法将返回QByteArray。然后,使用QByteArray::data()QByteArray::size() 传递给ParseFromArray(const void* data, int size)。您还需要在需要时处理错误。

这是一个例子:

bool open( const QString& filename )
{
    QFile file { filename };
    if ( !file.open( QIODevice::ReadOnly ) ) return false;

    const auto data = file.readAll();
    if ( data.isEmpty() ) return false;

    if ( !ParseFromArray( data.data(), data.size() ) ) return false;

    // successful parsing: process here...

    return true;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-30
    • 2013-07-10
    • 2018-06-05
    • 1970-01-01
    • 2019-04-26
    • 1970-01-01
    • 2013-06-22
    • 1970-01-01
    相关资源
    最近更新 更多