我需要一个文件的校验和,并找到这,它工作得很好。现在,我希望更改此函数,以获得指向前面用以下行打开的QIODevice的指针:
if (!file.open(QFile::ReadOnly | QFile::Text))
{
...
}这被传递到读取(reader.read(&file);)为设备:
bool XmlReader::read(QIODevice* device)
{
QByteArray b = fileChecksum(device);
...
}这是我的fileChecksum实现。它返回一个校验和,但我永远陷入循环,并得到一个xml解析错误。我在这里做错什么了?
QByteArray XmlReader::fileChecksum(QIODevice* device)
{
if (device->isOpen())
{
QCryptographicHash hash(QCryptographicHash::Sha256);
if (hash.addData(device)) {
return hash.result();
}
}
return QByteArray();
}编辑
就在QByteArray b = fileChecksum(device);之后我做了:
qDebug() << "Checksum: " << b.toHex();一直在印刷..。
解析错误是:premature end of document,这是垃圾。
希望这能有所帮助。
发布于 2016-11-16 12:59:15
由于最终导致错误的代码行没有出现,所以我只能猜测发生了什么。
函数fileChecksum调用hash.addData(device),它读取QIODevice直到结束并保持光标在那里的位置。
很可能之后您尝试从QIODevice中读取,这将解释premature end of documen消息。
作为一个快速的解决方法,您可以尝试重新设置位置之后,用
auto pos = device->pos();
QByteArray b = fileChecksum(device);
device->seek(pos);但是,如果可以的话,您应该只读取一次数据(为了支持非随机访问QIODevices )。例如,可以将结果存储在QBuffer中,并将其用作QIODevice。如下所示:
bool XmlReader::read(QIODevice* device)
{
QByteArray contents = device->readAll();
QBuffer buffer(&contents);
device = &buffer;//you can also just use &buffer from here on out instead of overwriting the pointer
QByteArray b = fileChecksum(device);
device->reset();
/* ... further reads from device here */
}https://stackoverflow.com/questions/40583840
复制相似问题