您的位置:首页 > 编程语言 > Qt开发

[Qt] 获取文件MD5码(支持大文件) [2012-03-28更新]

2013-05-21 00:07 344 查看
#include <QString>
#include <QByteArray>
#include <QCryptographicHash>
#include <QFile>
#include <QDebug>

QByteArray getFileMd5(QString filePath)
{
QFile localFile(filePath);

if (!localFile.open(QFile::ReadOnly))
{
qDebug() << "file open error.";
return 0;
}

QCryptographicHash ch(QCryptographicHash::Md5);

quint64 totalBytes = 0;
quint64 bytesWritten = 0;
quint64 bytesToWrite = 0;
quint64 loadSize = 1024 * 4;
QByteArray buf;

totalBytes = localFile.size();
bytesToWrite = totalBytes;

while (1)
{
if (bytesToWrite > 0)
{
buf = localFile.read(qMin(bytesToWrite, loadSize));
ch.addData(buf);
bytesWritten += buf.length();
bytesToWrite -= buf.length();
buf.resize(0);
}
else
{
break;
}

if (bytesWritten == totalBytes)
{
break;
}
}

localFile.close();
QByteArray md5 = ch.result();
return md5;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: