1

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 way of getting the list of physical storage disks.

I've found CreateFile(). But I cannot understand how to use it properly. I need a non-wmi solution. and it's better if it doesn't query registry.

Johan
  • 74,508
  • 24
  • 191
  • 319
Neel Basu
  • 12,638
  • 12
  • 82
  • 146

1 Answers1

4

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);
}
rodrigo
  • 94,151
  • 12
  • 143
  • 190
  • But this still gives me the Logical Disks `\Device\HarddiskVolume2` and `\Device\HarddiskVolume3` But both of them belongs to the same Physical Device .. I want to get That Physical device Information. – Neel Basu Sep 29 '11 at 06:05
  • The IOCTL_STORAGE_GET_DEVICE_NUMBER gives you the physical device number, in the `sdn.DeviceNumber` field. Just use then `sprintf(name, "\Device\PhysicalDrive\%d", (int)sdn.DeviceNumber)` or similar. Yes, you'll the same device serveral times, one per volume, but that's not a big deal. – rodrigo Sep 29 '11 at 07:22