SanekTNT
SanekTNT

Reputation: 21

Can not get directory size in QT C++

cur_file.size return 0, how I can solve this problem?

void MainWindow::setDirectory() {
QString directory_way = QFileDialog::getExistingDirectory(0, "Choose directory: ", "");
QFile cur_file(directory_way);
QFile fileOut("fileout.txt");
if(fileOut.open(QIODevice::WriteOnly | QIODevice::Text))
{
        QTextStream writeStream(&fileOut);
        writeStream << "You chose directory: " << directory_way <<" with size " << cur_file.size();
        fileOut.close();
}}

Upvotes: 2

Views: 5169

Answers (2)

Mike
Mike

Reputation: 8355

QFile::size() is meant to be used with files only, it can't calculate the size of a directory. Qt does not provide a function to do the latter out of the box, but it is not hard to write your own recursive function that iterates through the directory's files and directories, and adds their sizes...

Here is a complete example:

#include <QtWidgets>

qint64 dirSize(QString dirPath) {
    qint64 size = 0;
    QDir dir(dirPath);
    //calculate total size of current directories' files
    QDir::Filters fileFilters = QDir::Files|QDir::System|QDir::Hidden;
    for(QString filePath : dir.entryList(fileFilters)) {
        QFileInfo fi(dir, filePath);
        size+= fi.size();
    }
    //add size of child directories recursively
    QDir::Filters dirFilters = QDir::Dirs|QDir::NoDotAndDotDot|QDir::System|QDir::Hidden;
    for(QString childDirPath : dir.entryList(dirFilters))
        size+= dirSize(dirPath + QDir::separator() + childDirPath);
    return size;
}

QString formatSize(qint64 size) {
    QStringList units = {"Bytes", "KB", "MB", "GB", "TB", "PB"};
    int i;
    double outputSize = size;
    for(i=0; i<units.size()-1; i++) {
        if(outputSize<1024) break;
        outputSize= outputSize/1024;
    }
    return QString("%0 %1").arg(outputSize, 0, 'f', 2).arg(units[i]);
}

int main(int argc, char* argv[]) {
    QApplication a(argc, argv);

    QString directoryPath = QFileDialog
            ::getExistingDirectory(nullptr, "Choose directory: ", "");
    //calculate and output selected directory size
    qint64 size = dirSize(directoryPath);
    qInfo() << formatSize(size);

    QTimer::singleShot(0, &a, &QApplication::quit);
    return a.exec();
}

Upvotes: 8

mschmidt
mschmidt

Reputation: 2790

From the Qt documentation of QIODevice::size():

If the device is closed, the size returned will not reflect the actual size of the device.

Upvotes: 0

Related Questions