如何正确使用deviceiocontrol功能

时间:2016-05-05 09:50:09

标签: c winapi

这是我的代码:

代码:

HANDLE HandelUsb= CreateFile(L"\\\\.\\G:", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
if (HandelUsb == INVALID_HANDLE_VALUE)
{
    printf("Terminal failure: Unable to open usb ERROR CODE:0x%x\n", GetLastError());
    return 1;
}

DISK_GEOMETRY d = { 0 };
DWORD dwReturned = 0;

int gs =DeviceIoControl(HandelUsb, IOCTL_DISK_GET_DRIVE_GEOMETRY, NULL, 0, &d, sizeof(DISK_GEOMETRY),&dwReturned, NULL);
printf("%d\n", gs);

if (d.MediaType == RemovableMedia)
{
    DWORD dwReturned2 = 0;
    MEDIA_SERIAL_NUMBER_DATA data={ 0 };
    if (DeviceIoControl(HandelUsb, IOCTL_STORAGE_GET_MEDIA_SERIAL_NUMBER, NULL, 0, &data,sizeof(MEDIA_SERIAL_NUMBER_DATA), &dwReturned2, NULL)) {
            printf("SerialNumberLength %d\nResult %d\nReserved[2] %s\nSerialNumberData[1] %s ", data.SerialNumberLength, data.Result, data.Reserved, data.SerialNumberData);
    }
    else {
            printf("faild to get serial number ERROR CODE:0x%x\n", GetLastError());

    }
}

CloseHandle(HandelUsb);
return 0;

除了功能之外,一切都很顺利 代码:

DeviceIoControl(HandelUsb, IOCTL_STORAGE_GET_MEDIA_SERIAL_NUMBER, NULL, 0, &data,sizeof(MEDIA_SERIAL_NUMBER_DATA), &dwReturned2, NULL)

始终失败(返回值0),GetLastError返回值0X1(问题函数)。

也许有人在这里可以告诉我我在这里失踪了什么?

根据@IInspectable的评论,我将代码更改为:

    //volume handle to device handle
VOLUME_DISK_EXTENTS volumeToDevice = { 0 };
DWORD Returned = 0;
DeviceIoControl(HandelToUsb,IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS,NULL,0,&volumeToDevice,sizeof(VOLUME_DISK_EXTENTS),&Returned,NULL);


WCHAR volume[150] ;
swprintf_s(volume, L"\\\\.\\PhysicalDrive%d", volumeToDevice.Extents[0].DiskNumber);
wprintf(L"%s\n", volume);

//handle to phisicalDrive
HANDLE HandelUsb = CreateFile(volume, 0, FILE_SHARE_READ |FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
DWORD dwReturned2 = 0;
    MEDIA_SERIAL_NUMBER_DATA data={ 0 };
    if (DeviceIoControl(HandelUsb, IOCTL_STORAGE_GET_MEDIA_SERIAL_NUMBER, NULL, 0, &data,sizeof(MEDIA_SERIAL_NUMBER_DATA), &dwReturned2, NULL)) {
            printf("SerialNumberLength %d\nResult %d\nReserved[2] %s\nSerialNumberData[1] %s ", data.SerialNumberLength, data.Result, data.Reserved, data.SerialNumberData);
    }
    else {
            printf("faild to get serial number ERROR CODE:0x%x\n", GetLastError());

    }

我仍然在功能上失败0X1

 DeviceIoControl (Handel Usb, IOCTL_STORAGE_GET_MEDIA_SERIAL_NUMBER, NULL, 0, & data, sizeof (MEDIA_SERIAL_NUMBER_DATA), & dwReturned2, NULL)
  • 我跑了Windus 7
  • 我尝试更改权限函数CreateFile(添加GENERIC_EXECUTE,替换为GENERIC_ALL添加FILE_ATTRIBUTE_NORMAL),使用DeviceIoControl的参数进行播放。

0 个答案:

没有答案