summaryrefslogtreecommitdiffstats
path: root/helper.cpp
blob: d19cdf149e8f2c9241868604580a00519fb42251 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <QFile>
#include <QFileInfo>
#include <QCryptographicHash>
#include <QByteArray>

#include "helper.h"

namespace Helper {
    const QString md5Sum(const QString &path){
        QFileInfo info(path);
        if(!info.exists() || !info.isFile()){
            return QString();
        }

        QString retval;
        QCryptographicHash h(QCryptographicHash::Md5);
        QFile file(path);
        file.open(QIODevice::ReadOnly);
        qint64 read = 0;
        if(info.size() < (5 * 1024 * 1024)){
            QByteArray data(4096, '\0');
            do {
                read = file.read(data.data(), 4096);
                if(read > 0){
                    h.addData(data.data(), read);
                }
            } while (read == 4096);
            QByteArray res = h.result();
            retval = res.toHex().toLower();
        }else{
            QByteArray data(512, '\0');
            int offset = info.size() / 3;
            file.seek(offset);
            int numBytes = 512 * 1024;
            int readBytes = 0;
            do {
                read = file.read(data.data(), 512);
                if(read > 0){
                    readBytes += read;
                }else{
                    return QString();
                }
                h.addData(data.data(), read);
            } while(readBytes < numBytes);
            QByteArray res = h.result();
            retval = res.toHex().toLower();
        }
        return retval;
    }
}