How do I get the disk drive serial number in C/C++

The Mask picture The Mask · Jun 5, 2014 · Viewed 37.4k times · Source

This has been already answered but it's a C# solution. How do I do this in C or C++?

Answer

G-- picture G-- · Jun 5, 2014

There are a few ways to do this. You could make calls using system to get the information.

For Linux:

system("hdparm -i /dev/hda | grep -i serial");

Without using system:

static struct hd_driveid hd;
int fd;

if ((fd = open("/dev/hda", O_RDONLY | O_NONBLOCK)) < 0) {
    printf("ERROR opening /dev/hda\n");
    exit(1);
}

if (!ioctl(fd, HDIO_GET_IDENTITY, &hd)) {
    printf("%.20s\n", hd.serial_no);
} else if (errno == -ENOMSG) {
    printf("No serial number available\n");
} else {
    perror("ERROR: HDIO_GET_IDENTITY");
    exit(1);
}

For Windows:

system("wmic path win32_physicalmedia get SerialNumber");

Without using system (Based on Getting WMI Data ):

hres = pSvc->ExecQuery(
    bstr_t("WQL"),
    bstr_t("SELECT SerialNumber FROM Win32_PhysicalMedia"),
    WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, 
    NULL,
    &pEnumerator);
hr = pclsObj->Get(L"SerialNumber", 0, &vtProp, 0, 0);