如何确定 Qt 中驱动器上有多少可用空间?

发布于 2024-08-10 19:00:51 字数 330 浏览 5 评论 0原文

我正在使用 Qt,并且想要一种独立于平台的方式来获取可用的可用磁盘空间。

我知道在 Linux 中我可以使用 statfs,在 Windows 中我可以使用 GetDiskFreeSpaceEx()。我知道boost有办法,boost::filesystem::space(Path const & p)

但我不想要那些。我在 Qt 中,想以 Qt 友好的方式来做。

我查看了QDirQFileQFileInfo——什么也没有!

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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

傲世九天 2024-08-17 19:00:51

我知道这是一个很老的话题,但有人仍然会发现它很有用。

自 QT 5.4 起,QSystemStorageInfo 已不再使用,取而代之的是一个新的类 QStorageInfo,它使整个任务变得非常简单,并且是跨平台的。

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()/1024/1024 << "MB";
qDebug() << "availableSize:" << storage.bytesAvailable()/1024/1024 << "MB";

代码已从 QT 5.5 文档中的示例复制

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()/1024/1024 << "MB";
qDebug() << "availableSize:" << storage.bytesAvailable()/1024/1024 << "MB";

Code has been copied from the example in QT 5.5 docs

泪眸﹌ 2024-08-17 19:00:51

Qt 5.4 中引入的新 QStorageInfo 类可以做到这一点(以及更多)。它是 Qt Core 模块的一部分,因此不需要额外的依赖项。

#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";
}

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";
}
豆芽 2024-08-17 19:00:51

我在写问题时写了这篇文章(在 QTBUG-3780 投票后) );我想我可以让某人(或我自己)免于从头开始做这件事。

这是针对 Qt 4.8.x 的。

#ifdef WIN32
/*
 * getDiskFreeSpaceInGB
 *
 * Returns the amount of free drive space for the given drive in GB. The
 * value is rounded to the nearest integer value.
 */
int getDiskFreeSpaceInGB( LPCWSTR drive )
{
    ULARGE_INTEGER freeBytesToCaller;
    freeBytesToCaller.QuadPart = 0L;

    if( !GetDiskFreeSpaceEx( drive, &freeBytesToCaller, NULL, NULL ) )
    {
        qDebug() << "ERROR: Call to GetDiskFreeSpaceEx() failed.";
    }

    int freeSpace_gb = freeBytesToCaller.QuadPart / B_per_GB;
    qDebug() << "Free drive space: " << freeSpace_gb << "GB";

    return freeSpace_gb;
}
#endif

用法:

// Check available hard drive space
#ifdef WIN32
        // The L in front of the string does some WINAPI magic to convert
        // a string literal into a Windows LPCWSTR beast.
        if( getDiskFreeSpaceInGB( L"c:" ) < MinDriveSpace_GB )
        {
            errString = "ERROR: Less than the recommended amount of free space available!";
            isReady = false;
        }
#else
#    pragma message( "WARNING: Hard drive space will not be checked at application start-up!" )
#endif

I wrote this back when I wrote the question (after voting on QTBUG-3780); I figure I'll save someone (or myself) from doing this from scratch.

This is for Qt 4.8.x.

#ifdef WIN32
/*
 * getDiskFreeSpaceInGB
 *
 * Returns the amount of free drive space for the given drive in GB. The
 * value is rounded to the nearest integer value.
 */
int getDiskFreeSpaceInGB( LPCWSTR drive )
{
    ULARGE_INTEGER freeBytesToCaller;
    freeBytesToCaller.QuadPart = 0L;

    if( !GetDiskFreeSpaceEx( drive, &freeBytesToCaller, NULL, NULL ) )
    {
        qDebug() << "ERROR: Call to GetDiskFreeSpaceEx() failed.";
    }

    int freeSpace_gb = freeBytesToCaller.QuadPart / B_per_GB;
    qDebug() << "Free drive space: " << freeSpace_gb << "GB";

    return freeSpace_gb;
}
#endif

Usage:

// Check available hard drive space
#ifdef WIN32
        // The L in front of the string does some WINAPI magic to convert
        // a string literal into a Windows LPCWSTR beast.
        if( getDiskFreeSpaceInGB( L"c:" ) < MinDriveSpace_GB )
        {
            errString = "ERROR: Less than the recommended amount of free space available!";
            isReady = false;
        }
#else
#    pragma message( "WARNING: Hard drive space will not be checked at application start-up!" )
#endif
调妓 2024-08-17 19:00:51

在撰写本文时,Qt 中还没有任何内容。

考虑对 QTBUG-3780 发表评论或投票。

There is nothing in Qt at time of writing.

Consider commenting on or voting for QTBUG-3780.

乖乖 2024-08-17 19:00:51

我需要写入已安装的 USB 记忆棒,并使用以下代码获取可用内存大小:

QFile usbMemoryInfo;
QStringList usbMemoryLines;
QStringList usbMemoryColumns;

system("df /dev/sdb1 > /tmp/usb_usage.info");
usbMemoryInfo.setFileName( "/tmp/usb_usage.info" );

usbMemoryInfo.open(QIODevice::ReadOnly);

QTextStream readData(&usbMemoryInfo);

while (!readData.atEnd())
{
    usbMemoryLines << readData.readLine();
}

usbMemoryInfo.close();

usbMemoryColumns = usbMemoryLines.at(1).split(QRegExp("\\s+"));
QString available_bytes = usbMemoryColumns.at(3);

I need to write to a mounted USB-Stick and I got the available size of memory with the following code:

QFile usbMemoryInfo;
QStringList usbMemoryLines;
QStringList usbMemoryColumns;

system("df /dev/sdb1 > /tmp/usb_usage.info");
usbMemoryInfo.setFileName( "/tmp/usb_usage.info" );

usbMemoryInfo.open(QIODevice::ReadOnly);

QTextStream readData(&usbMemoryInfo);

while (!readData.atEnd())
{
    usbMemoryLines << readData.readLine();
}

usbMemoryInfo.close();

usbMemoryColumns = usbMemoryLines.at(1).split(QRegExp("\\s+"));
QString available_bytes = usbMemoryColumns.at(3);
蝶舞 2024-08-17 19:00:51

我知道这个问题现在已经很老了,但是我搜索了 stackoverflow 并发现没有人找到解决方案,所以我决定发布。

QtMobility中有QSystemStorageInfo类,它提供了跨平台的方式来获取有关逻辑驱动器的信息。例如:逻辑驱动器()返回路径列表,您可以将其用作其他方法的参数:availableDiskSpace()totalDiskSpace()来获取相应的可用空间和总驱动器空间(以字节为单位)。

使用示例:

QtMobility::QSystemStorageInfo sysStrgInfo;
QStringList drives = sysStrgInfo.logicalDrives();

foreach (QString drive, drives)
{
    qDebug() << sysStrgInfo.availableDiskSpace(drive);
    qDebug() << sysStrgInfo.totalDiskSpace(drive);
}

此示例打印操作系统中所有逻辑驱动器的可用空间和总空间(以字节为单位)。不要忘记在 Qt 项目文件中添加 QtMobility

CONFIG += mobility
MOBILITY += systeminfo

我在我现在正在处理的项目中使用了这些方法,并且它对我有用。希望它能帮助别人!

I know that this question is already quite old by now, but I searched stackoverflow and found that nobody got solution for this, so I decided to post.

There is QSystemStorageInfo class in QtMobility, it provides cross-platform way to get info about logical drives. For example: logicalDrives() returns list of paths which you can use as parameters for other methods: availableDiskSpace(), totalDiskSpace() to get free and total drive's space, accordingly, in bytes.

Usage example:

QtMobility::QSystemStorageInfo sysStrgInfo;
QStringList drives = sysStrgInfo.logicalDrives();

foreach (QString drive, drives)
{
    qDebug() << sysStrgInfo.availableDiskSpace(drive);
    qDebug() << sysStrgInfo.totalDiskSpace(drive);
}

This example prints free and total space in bytes for all logical drives in OS. Don't forget to add QtMobility in Qt project file:

CONFIG += mobility
MOBILITY += systeminfo

I used these methods in a project I'm working on now and it worked for me. Hope it'll help someone!

木槿暧夏七纪年 2024-08-17 19:00:51

这段代码对我有用:

#ifdef _WIN32 //win
    #include "windows.h"
#else //linux
    #include <sys/stat.h>
    #include <sys/statfs.h>
#endif


bool GetFreeTotalSpace(const QString& sDirPath, double& fTotal, double& fFree)
{
    double fKB = 1024;

    #ifdef _WIN32

        QString sCurDir = QDir::current().absolutePath();
        QDir::setCurrent(sDirPath);

        ULARGE_INTEGER free,total;

        bool bRes = ::GetDiskFreeSpaceExA( 0 , &free , &total , NULL );

        if ( !bRes )
            return false;

        QDir::setCurrent( sCurDir );

        fFree = static_cast<__int64>(free.QuadPart)  / fKB;
        fTotal = static_cast<__int64>(total.QuadPart)  / fKB;

    #else // Linux

        struct stat stst;
        struct statfs stfs;

        if ( ::stat(sDirPath.toLocal8Bit(),&stst) == -1 )
            return false;

        if ( ::statfs(sDirPath.toLocal8Bit(),&stfs) == -1 )
            return false;

        fFree = stfs.f_bavail * ( stst.st_blksize / fKB );
        fTotal = stfs.f_blocks * ( stst.st_blksize / fKB );

    #endif // _WIN32

    return true;
}

this code`s working for me:

#ifdef _WIN32 //win
    #include "windows.h"
#else //linux
    #include <sys/stat.h>
    #include <sys/statfs.h>
#endif


bool GetFreeTotalSpace(const QString& sDirPath, double& fTotal, double& fFree)
{
    double fKB = 1024;

    #ifdef _WIN32

        QString sCurDir = QDir::current().absolutePath();
        QDir::setCurrent(sDirPath);

        ULARGE_INTEGER free,total;

        bool bRes = ::GetDiskFreeSpaceExA( 0 , &free , &total , NULL );

        if ( !bRes )
            return false;

        QDir::setCurrent( sCurDir );

        fFree = static_cast<__int64>(free.QuadPart)  / fKB;
        fTotal = static_cast<__int64>(total.QuadPart)  / fKB;

    #else // Linux

        struct stat stst;
        struct statfs stfs;

        if ( ::stat(sDirPath.toLocal8Bit(),&stst) == -1 )
            return false;

        if ( ::statfs(sDirPath.toLocal8Bit(),&stfs) == -1 )
            return false;

        fFree = stfs.f_bavail * ( stst.st_blksize / fKB );
        fTotal = stfs.f_blocks * ( stst.st_blksize / fKB );

    #endif // _WIN32

    return true;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文