//头文件
#include <QDebug>
#include <QByteArray>
#include <QString>
#include <QIODevice>
#include <QFile>
#include <QCryptographicHash>
The first:
If the file is not very large, you can read the file content at one time to get the md5 of the file.
//获取文件MD5或者Sha1码等 参数 = 文件路径
void test::readFileMd5(QString filePath)
{
QFile file(filePath);
if(file.open(QIODevice::ReadOnly)){
qDebug() << "打开文件成功";
//这里 QCryptographicHash::Md5 是个枚举类型,可以说改成你需要的比如Sha1、Sha3
QByteArray ba = QCryptographicHash::hash(file.readAll(), QCryptographicHash::Md5);
qDebug() << ba.toHex(); //打印MD5码,或改成你的返回
file.close();
}else{
qDebug() << "打开文件失败";
}
}
the second
For large files, one-time reading will not have enough memory, so read the contents of the file in sections to obtain the file md5.
//分段读取生成MD5码- 参数=文件路径
void test::readFileMd5_1(QString filePath)
{
QFile file(filePath);
QCryptographicHash hash(QCryptographicHash::Md5);
if(file.open(QIODevice::ReadOnly))//打开文件
{
while(!file.atEnd())
{
QByteArray content = file.read(1024 * 1024 * 100);
hash.addData(content);
}
QByteArray md5 = hash.result();
//打印MD5码
qDebug() << "MD5:" << md5.toHex();
file.close();
}
else
{
qDebug() << "打开文件失败";
}
}
Supplement: call example
//弹出文件选择框
QString fileName = QFileDialog::getOpenFileName(this,QStringLiteral("文件对话框!"),"F:",QStringLiteral("所有文件(*.*)"));
//调用第一种-如果方法需要返回,请自行修改方法返回值
readFileMd5(fileName);
//调用第二种-如果方法需要返回,请自行修改方法返回值
readFileMd5_1(fileName);