使用QCryptographicHash对文件进行MD5计算。用来检测文件是否改变

6 篇文章 0 订阅

占个坑,有空写。先把代码传上来。

#include "c4hashcrypt.h"
#include <QFile>
#include <QTextCodec>
#include <QTextStream>
#include <QCryptographicHash>
#include <QDebug>
/***********************************************************
 * 遍历大文件16g大概2分多,如果是零碎文件5g大概6分钟
 * ********************************************************/


C4HashCrypt::C4HashCrypt(QObject *parent) :
    QObject(parent)
{

}
bool C4HashCrypt::md5Files(QStringList fileList, QString hashFile)
{
    QFile hM5file(hashFile);
    QString lastest("Desktop/");
    if(hM5file.open(QFile::Truncate|QFile::WriteOnly|QFile::Text))
    {
        foreach (QString file, fileList) {
             QByteArray bb = md5file(file);
             bb.append("    [file]= ");
             file =file.right(file.size()-file.lastIndexOf(lastest));//去掉指定文件路径~
             file = file.right(file.size()-QString(lastest).size());
             bb.append(file);
             bb.append('\n');
             hM5file.write(bb);
        }
        hM5file.close();
        return true;
    }
    else
    {
        qDebug()<<"openHM5file False";
        return false;
    }
}

QByteArray C4HashCrypt::md5file(QString fileName)
{
    QByteArray md5C = Q_NULLPTR;
    QFile file(fileName);
   // QTextCodec  *code = QTextCodec::codecForName("utf8");
    if(file.exists())
    {
        if(file.open(QFile::ReadOnly))
        {
#if 0
            QTextStream  stream(&file);//如果用这种方法则会导致加密rar文件报错。
            stream.setCodec(code);
            QString data;
            data = stream.readAll();

            md5C = QCryptographicHash::hash(data.toLatin1(),\
                                            QCryptographicHash::Md5).toHex();//必须有.toHex();
#else
            QCryptographicHash hash(QCryptographicHash::Md5);
            hash.addData(&file);
            md5C = hash.result().toHex();
#endif
            file.close();
        }else
        {
            qDebug()<<"open file False";
        }
    }else
    {
        qDebug()<<"file is not exit";
    }
    return md5C;
}


  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值