Search code examples
c++linuxqtqt5qdir

[Qt][Linux] List drive or partitions


How I can list drives or mounted partitions using qt? I tried to use:

foreach( QFileInfo drive, QDir::drives() )
       {
         qDebug() << "Drive: " << drive.absolutePath();
       }

but it shows just root drive. I also noticed that length of QDir::drives() is 1 but QDir::Drives is 4.


Solution

  • You can use /etc/mtab file to obtain a mountpoints list.

    QFile file("/etc/mtab");
    if (file.open(QFile::ReadOnly)) {
      QStringList mountpoints;
      while(true) {
        QStringList parts = QString::fromLocal8Bit(file.readLine()).trimmed().split(" ");
        if (parts.count() > 1) {
          mountpoints << parts[1];
        } else {
          break;
        }
      }
      qDebug() << mountpoints;
    }
    

    Output on my machine:

    ("/", "/proc", "/sys", "/sys/fs/cgroup", "/sys/fs/fuse/connections", "/sys/kernel/debug", "/sys/kernel/security", "/dev", "/dev/pts", "/run", "/run/lock", "/run/shm", "/run/user", "/media/sf_C_DRIVE", "/media/sf_C_DRIVE", "/media/sf_D_DRIVE", "/run/user/ri/gvfs")

    Note that QFile::atEnd() always returns true for this file, so I didn't use it in my code.

    QDir::Drives is 4 according to the documentation. It's static integer value of enum item, it doesn't show anything and you shouldn't care about it in most cases. QDir::drives() contains exactly one item (for root filesystems) when executed on Linux.