首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用C++中的WMI来获得硬盘所有逻辑驱动器的空闲空间?

如何使用C++中的WMI来获得硬盘所有逻辑驱动器的空闲空间?
EN

Stack Overflow用户
提问于 2016-04-26 07:10:06
回答 2查看 914关注 0票数 0

我想使用c++和WMI计算整个硬盘的空闲空间。

例如。如果HDD包含3个逻辑驱动器,比如C:,D:,E:,并且每个逻辑驱动器的配置如下。

驱动全空间自由空间

C: 10 GB 5 GB D: 20 GB 8 GB E: 15 GB 7 GB

因此,我需要获取免费硬盘空间,即所有驱动器的空闲空间C、D和E。

因此,它应该返回5+8+7 = 20 GB。

另外,我也不知道那个硬盘存在什么逻辑驱动器。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-04-26 07:29:50

非WMI是容易得多。

您可以使用GetLogicalDriveStrings (https://msdn.microsoft.com/en-us/library/windows/desktop/aa364975(v=vs.85).aspx )获取系统中的所有驱动器。

接下来,使用GetDiskFreeSpace (https://msdn.microsoft.com/en-us/library/windows/desktop/aa364935(v=vs.85).aspx )查找特定驱动器的空闲空间。

如果你真的想(必须)坚持WMI,页面https://msdn.microsoft.com/en-us/library/windows/desktop/aa393244(v=vs.85).aspx将给出一些关于如何实例化WMI类的说明,并且您需要使用Win32_LogicalDisk (有FreeSpace成员的https://msdn.microsoft.com/en-us/library/windows/desktop/aa394173(v=vs.85).aspx类)。

票数 0
EN

Stack Overflow用户

发布于 2022-04-27 21:21:15

这是一个充分发挥作用的功能,将使您在所有驱动器的自由空间。它以CString的形式生成结果,但当然可以返回一个数字(字节数)。

代码语言:javascript
复制
CString GetFreeDiskSpace()
{
    CString str_result{ L"" };
    DWORD cchBuffer;
    WCHAR stddriveStrings[2048];
    WCHAR *driveSetings = &stddriveStrings[0];
    UINT driveType;
    PWSTR driveTypeString;
    ULARGE_INTEGER freeSpace;

    // Find out the required buffer size that we need
    cchBuffer = GetLogicalDriveStrings(0, NULL);


    // Fetch all drive letters as strings 
    GetLogicalDriveStrings(cchBuffer, driveSetings);

    // Loop until we reach the end (by the '\0' char)
    // driveStrings is a double null terminated list of null terminated strings)
    while (*driveSetings)
    {
        // Dump drive information
        driveType = GetDriveType(driveSetings);
        GetDiskFreeSpaceEx(driveSetings, &freeSpace, NULL, NULL);

        switch (driveType)
        {
            case DRIVE_FIXED:
                driveTypeString = L"Hard Drive";
                break;

            case DRIVE_CDROM:
                driveTypeString = L"CD/DVD";
                break;

            case DRIVE_REMOVABLE:
                driveTypeString = L"Removable";
                break;

            case DRIVE_REMOTE:
                driveTypeString = L"Network";
                break;

            default:
                driveTypeString = L"Unknown";
                break;
        }

        str_result.Format(L"%s\n%s - %s - %I64u GB free", 
            str_result, driveSetings, driveTypeString,
            freeSpace.QuadPart / 1024 / 1024 / 1024);

  // Move to next drive string
  // +1 is to move past the null at the end of the string.
        driveSetings += _tcsclen(driveSetings) + 1;
    }


    return str_result;

}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36857720

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档