【Qt】获取文件MD5码(支持大文件)【2012-03-28 更新】
1 #include <QString>
2 #include <QByteArray>
3 #include <QCryptographicHash>
4 #include <QFile>
5 #include <QDebug>
6
7 QByteArray getFileMd5(QString filePath)
8 {
9 QFile localFile(filePath);
10
11 if (!localFile.open(QFile::ReadOnly))
12 {
13 qDebug() << "file open error.";
14 return 0;
15 }
16
17 QCryptographicHash ch(QCryptographicHash::Md5);
18
19 quint64 totalBytes = 0;
20 quint64 bytesWritten = 0;
21 quint64 bytesToWrite = 0;
22 quint64 loadSize = 1024 * 4;
23 QByteArray buf;
24
25 totalBytes = localFile.size();
26 bytesToWrite = totalBytes;
27
28 while (1)
29 {
30 if(bytesToWrite > 0)
31 {
32 buf = localFile.read(qMin(bytesToWrite, loadSize));
33 ch.addData(buf);
34 bytesWritten += buf.length();
35 bytesToWrite -= buf.length();
36 buf.resize(0);
37 }
38 else
39 {
40 break;
41 }
42
43 if(bytesWritten == totalBytes)
44 {
45 break;
46 }
47 }
48
49 localFile.close();
50 QByteArray md5 = ch.result();
51 return md5;
52 }