如何获取物理存储设备列表?

时间:2011-09-28 14:12:19

标签: c++ winapi visual-c++ storage

我想获得一个物理存储设备列表 我见过一些代码,但实际上是循环,并做了类似暴力的事情 我想知道获取物理存储磁盘列表的一般方法是什么。

我找到了CreateFile()。但我无法理解如何正确使用它。我需要一个非wmi解决方案。如果它不查询注册表,那就更好了。

1 个答案:

答案 0 :(得分:3)

我使用了以下代码,它枚举了所有卷,然后查找相应的物理驱动器:

#include <windows.h>
#include <commctrl.h>
#include <winioctl.h>

typedef struct _STORAGE_DEVICE_NUMBER {
  DEVICE_TYPE  DeviceType;
  ULONG  DeviceNumber;
  ULONG  PartitionNumber;
} STORAGE_DEVICE_NUMBER, *PSTORAGE_DEVICE_NUMBER;

void PrintVolumes()
{
    char volName[MAX_PATH];
    HANDLE hFVol;
    DWORD bytes;

    hFVol = FindFirstVolume(volName, sizeof(volName));
    if (!hFVol)
    {
        printf("error...\n");
        return;
    }
    do
    {
        size_t len = strlen(volName);
        if (volName[len-1] == '\\')
        {
            volName[len-1] = 0;
            --len;
        }

        /* printf("OpenVol %s\n", volName); */
        HANDLE hVol = CreateFile(volName, 0, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
        if (hVol == INVALID_HANDLE_VALUE)
            continue;

        STORAGE_DEVICE_NUMBER sdn = {0};
        if (!DeviceIoControl(hVol, IOCTL_STORAGE_GET_DEVICE_NUMBER, NULL,
                    0, &sdn, sizeof(sdn), &bytes, NULL))
        {
            printf("error...\n");
            continue;
        }
        CloseHandle(hVol);

        printf("Volume Type:%d, Device:%d, Partition:%d\n", (int)sdn.DeviceType, (int)sdn.DeviceNumber, (int)sdn.PartitionNumber);
        /* if (sdn.DeviceType == FILE_DEVICE_DISK)
            printf("\tIs a disk\n");
            */
    } while (FindNextVolume(hFVol, volName, sizeof(volName)));
    FindVolumeClose(hFVol);
}