Qt 计算文件(含超大文件)的 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 超大文件的进行测试

10.1 GB 超大文件

测试结果如下:

测试结果

本文参考链接:
http://www.qtcentre.org/threads/47635-Calculate-MD5-sum-of-a-big-file

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,665评论 19 139
  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,353评论 0 33
  • 首页 资讯 文章 资源 小组 相亲 登录 注册 首页 最新文章 IT 职场 前端 后端 移动端 数据库 运维 其他...
    Helen_Cat阅读 9,411评论 1 10
  • 贵族学校的起源是英国的皇室家族为孩子请的家庭教师,后来随着时间推移,社会的需求量就演化了今天的贵族学...
    九宫格格阅读 4,470评论 0 0
  • 我收藏了两个泡菜坛子,一个是六朝青瓷泡菜坛子,高11.6厘米,距今约1700年。一个是酱釉泡菜坛子,高36.3厘米...
    吾吾斋阅读 4,402评论 0 0