How to determine how much free space on a drive in Qt?


Question

I'm using Qt and want a platform-independent way of getting the available free disk space.

I know in Linux I can use statfs and in Windows I can use GetDiskFreeSpaceEx(). I know boost has a way, boost::filesystem::space(Path const & p).

But I don't want those. I'm in Qt and would like to do it in a Qt-friendly way.

I looked at QDir, QFile, QFileInfo -- nothing!

1
15
10/16/2016 9:55:36 AM

Accepted Answer

I know It's quite old topic but somebody can still find it useful.

Since QT 5.4 the QSystemStorageInfo is discontinued, instead there is a new class QStorageInfo that makes the whole task really simple and it's cross-platform.

QStorageInfo storage = QStorageInfo::root();

qDebug() << storage.rootPath();
if (storage.isReadOnly())
    qDebug() << "isReadOnly:" << storage.isReadOnly();

qDebug() << "name:" << storage.name();
qDebug() << "fileSystemType:" << storage.fileSystemType();
qDebug() << "size:" << storage.bytesTotal()/1000/1000 << "MB";
qDebug() << "availableSize:" << storage.bytesAvailable()/1000/1000 << "MB";

Code has been copied from the example in QT 5.5 docs

24
11/23/2015 4:06:48 PM

The new QStorageInfo class, introduced in Qt 5.4, can do this (and more). It's part of the Qt Core module so no additional dependencies required.

#include <QStorageInfo>
#include <QDebug>

void printRootDriveInfo() {
   QStorageInfo storage = QStorageInfo::root();

   qDebug() << storage.rootPath();
   if (storage.isReadOnly())
       qDebug() << "isReadOnly:" << storage.isReadOnly();

   qDebug() << "name:" << storage.name();
   qDebug() << "filesystem type:" << storage.fileSystemType();
   qDebug() << "size:" << storage.bytesTotal()/1024/1024 << "MB";
   qDebug() << "free space:" << storage.bytesAvailable()/1024/1024 << "MB";
}

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon