QT 获取文件MD5值

来源:互联网 发布:淘宝网天猫女童装 编辑:程序博客网 时间:2024/05/06 07:01
/* 方法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;}


0 0