问题
I am trying to identify if a drive is system reserved drive(PhysicalDrive0
or C-Drive
) using DeviceIoControl
function. However my code is always returning true for all the drives.
HANDLE hDevice; // handle to the drive to be examined
BOOL bResult; // results flag
DWORD junk; // discard results
PARTITION_INFORMATION_MBR *pdg
hDevice = CreateFile(TEXT("\\\\.\\C:"), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ |
FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
bResult = DeviceIoControl(
hDevice, // device to be queried
IOCTL_DISK_GET_PARTITION_INFO_EX, // operation to perform
NULL, 0, // no input buffer
pdg, sizeof(*pdg), // output buffer
&junk, // # bytes returned
(LPOVERLAPPED) NULL // synchronous I/O
);
bResult
isalways returning 0, indicating that the function succeeded.- Even
pdg->PartitionType
has junk information and not returningtrue
.
回答1:
bResult isalways returning 0, indicating that the function succeeded.
Plain wrong, the documentation states If the operation completes successfully, the return value is nonzero. Many things could be wrong, at least your parameters are not right and GetLastError
would have returned ERROR_INSUFFICIENT_BUFFER
:
You're giving DeviceIoControl
a uninitialized pointer, but it expects that pdg
points to a buffer, in this case, with the size of a pointer to PARTITION_INFORMATION_MBR
. Dereferencing wild pointers invokes undefined behavior. Also, according to the documentation DeviceIoControl
with OCTL_DISK_GET_PARTITION_INFO
awaits a PARTITION_INFORMATION_EX
structure so
Change
PARTITION_INFORMATION_MBR *pdg(;)
to
PARTITION_INFORMATION_EX pdg;
So you got a structure with automatic storage, for which you can give DeviceIoControl
a temporary pointer to it, with the &
operator.
bResult = DeviceIoControl(
hDevice, // device to be queried
IOCTL_DISK_GET_PARTITION_INFO_EX, // operation to perform
NULL, 0, // no input buffer
&pdg, sizeof(pdg), // output buffer
&junk, // # bytes returned
(LPOVERLAPPED) NULL // synchronous I/O
);
来源:https://stackoverflow.com/questions/12488337/identifying-system-reserved-drive-using-deviceiocontrol-function-in-c