How to get a list of physical storage devices?

前端 未结 1 332
闹比i
闹比i 2021-01-24 05:49

I want to get a list of physical storage devices.
I\'ve seen some code but that actually loops and does something like brute force.
I want to know what is the general wa

相关标签:
1条回答
  • 2021-01-24 06:28

    I've used the following code, that enumerates all the volumes and then looks for their corresponding physical drives:

    #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);
    }
    
    0 讨论(0)
提交回复
热议问题