所以我有一个二进制文件,它的名称作为const QString& filename
传递到我的函数中,我正试图将它读取到ProtoBuf中。我尝试过ParseFromArray(file.data(), file.size())
的例子,但它不起作用,大小为1
。
正确的方法是什么?非常感谢。
以下是我的相关代码片段:
bool open(const QString& filename)
{
myProject::protobuf::Example _example;
// need to copy contents from file to _example
}
您需要首先使用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;
}