QT 计算文件夹总大小并转换为B、KB、M、G

一、计算文件夹总大小

qint64 fileSize(const QString &path)
{
     
     QDir dir(path);
     qint64 size = 0;

     foreach(QFileInfo fileInfo, dir.entryInfoList(QDir::Files)) {
     
         size += fileInfo.size();
     }

     foreach(QString subDir, dir.entryList(QDir::Dirs|QDir::NoDotAndDotDot)) {
     
         size += fileSize(path + QDir::separator() + subDir);
     }

     return size;
}

二、转换大小单位

QString change(const qint64 &size)
{
     
    int integer = 0;  //整数位
    int decimal = 0;  //小数位,保留三位
    char unit ='B';
    qint64 standardSize = size;
    qint64 curSize = size;

    if(standardSize > 1024) {
     
        curSize = standardSize * 1000;
        curSize /= 1024;
        integer = curSize / 1000;
        decimal = curSize % 1000;
        standardSize /= 1024;
        unit = 'K';
        if(standardSize > 1024) {
     
            curSize = standardSize * 1000;
            curSize /= 1024;
            integer = curSize / 1000;
            decimal = curSize % 1000;
            standardSize /= 1024;
            unit = 'M';
            if(standardSize > 1024) {
     
                curSize = standardSize * 1000;
                curSize /= 1024;
                integer = curSize / 1000;
                decimal = curSize % 1000;
                unit = 'G';
            }
        }
    }

    QString dec = "0";
    if (0 <= decimal && decimal <= 9) {
     
        dec = dec + dec + QString::number(decimal);
    }

    if (10 <= decimal && decimal <= 99) {
     
        dec = "0" + QString::number(decimal);
    }

    if (100 <= decimal && decimal <= 999) {
     
        dec = QString::number(decimal);
    }

    return QString::number(integer) + "." + dec + unit;
}

你可能感兴趣的:(QT)