Domanda

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.

È stato utile?

Soluzione

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.

Altri suggerimenti

You need to use platform specific code. And, please, read the docs!

Returns a list of the root directories on this system.

On Windows this returns a list of QFileInfo objects containing "C:/", "D:/", etc. On other operating systems, it returns a list containing just one root directory (i.e. "/").

Qt 5.4+

You can use QStorageInfo class in Qt 5.4+ as follow:

foreach (const QStorageInfo &storage, QStorageInfo::mountedVolumes()) {
    if (storage.isValid() && storage.isReady()) {
        if (!storage.isReadOnly()) {
            // ...
        }
    }
}

more info

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top