物理硬盘命名为\\.\PhysicalDrive0
用CreateFile打开物理硬盘,然后用DeviceIoControl的参数IOCTL_DISK_GET_DRIVE_GEOMETRY,代码如下
#include <windows.h>
#include <stdio.h>
#include <winioctl.h>
#define wszDrive L"\\\\.\\PhysicalDrive0"
BOOL GetDriveGeometry(LPWSTR wszPath, DISK_GEOMETRY *pdg)
{
HANDLE hDevice = INVALID_HANDLE_VALUE;
BOOL bResult = FALSE;
DWORD junk = 0;
hDevice = CreateFile(wszDrive,
0,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
0,
NULL);
if (hDevice == INVALID_HANDLE_VALUE) return FALSE;
bResult = DeviceIoControl(hDevice,
IOCTL_DISK_GET_DRIVE_GEOMETRY,
NULL,
0,
pdg,
sizeof(*pdg),
&junk,
NULL);
CloseHandle(hDevice);
return TRUE;
}
int main()
{
DISK_GEOMETRY dg = {0};
BOOL bResult = FALSE;
ULONGLONG DiskSize = 0;
bResult = GetDriveGeometry(wszDrive, &dg);
if (bResult) {
wprintf(L"Drive path =%ws\n", wszDrive);
wprintf(L"Cylinders = %I64d\n", dg.Cylinders);
wprintf(L"Tracks/cylinder=%ld\n", dg.TracksPerCylinder);
wprintf(L"Sectors/track=%ld\n", dg.SectorsPerTrack);
wprintf(L"Bytes/sector=%ld\n", dg.BytesPerSector);
DiskSize = dg.Cylinders.QuadPart * (ULONG)dg.TracksPerCylinder * (ULONG)dg.SectorsPerTrack * (ULONG)dg.BytesPerSector;
wprintf(L"Disk size=%I64d (Bytes)"
L" %.2f (Gb)\n",
DiskSize,
(double)DiskSize / (1024 * 1024 * 1024));
} else {
wprintf(L"GetDriveGeometry failed. error:%ld.\n", GetLastError());
}
return 0;
}