/* 方法1 */
QFile theFile(fileNamePath);
theFile.open(QIODevice::ReadOnly);
QByteArray ba = QCryptographicHash::hash(theFile.readAll(), QCryptographicHash::Md5);
theFile.close();
qDebug() << ba.toHex().constData();
/* 方法2 */
/*
* 获取文件md5值
*/
QByteArray MainWindow::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;
}

Qt 计算文件(含超大文件)的 md5 值 

//大文件MD5
QString fileMd5(const QString &sourceFilePath) {

QFile sourceFile(sourceFilePath);
qint64 fileSize = sourceFile.size();
const qint64 bufferSize = 10240;

if (sourceFile.open(QIODevice::ReadOnly)) {
char buffer[bufferSize];
int bytesRead;
int readSize = qMin(fileSize, bufferSize);

QCryptographicHash hash(QCryptographicHash::Md5);

while (readSize > 0 && (bytesRead = sourceFile.read(buffer, readSize)) > 0) {
fileSize -= bytesRead;
hash.addData(buffer, bytesRead);
readSize = qMin(fileSize, bufferSize);
}

sourceFile.close();
return QString(hash.result().toHex());
}
return QString();
}

包含测试的完整代码如下:

#include <QCoreApplication>
#include <QCryptographicHash>
#include <QFile>
#include <QDebug>

QString fileMd5(const QString &sourceFilePath) {

QFile sourceFile(sourceFilePath);
qint64 fileSize = sourceFile.size();
const qint64 bufferSize = 10240;

if (sourceFile.open(QIODevice::ReadOnly)) {
char buffer[bufferSize];
int bytesRead;
int readSize = qMin(fileSize, bufferSize);

QCryptographicHash hash(QCryptographicHash::Md5);

while (readSize > 0 && (bytesRead = sourceFile.read(buffer, readSize)) > 0) {
fileSize -= bytesRead;
hash.addData(buffer, bytesRead);
readSize = qMin(fileSize, bufferSize);
}

sourceFile.close();
return QString(hash.result().toHex());
}
return QString();
}

int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);

QString md5("0e40d388359b41334831b898262cfe93"); // 使用 md5sum 命令获取

QString result = fileMd5("/home/toby/bin/Tools.zip");
qDebug() << "source MD5: " << md5;
qDebug() << "result MD5: " << result;
qDebug() << "is equal: " << (result == md5);
return a.exec();
}

使用 10.1 GB 超大文件的进行测试

QT 获取文件MD5值_#include

10.1 GB 超大文件

测试结果如下:

QT 获取文件MD5值_Qt_02