一般若要得到Sata硬碟或Usb硬碟Size,須要透過傳遞PASS_THROUGH參數來下Identify command,而參數須符合ATA command/ SCSI command spec, 使用上比較麻煩。
WinApi提供了一個比較通用的方式(IOCTL_DISK_GET_LENGTH_INFO)來得到,如下:
#include <windows.h>
#include <winioctl.h>
#include <stdio.h>
unsigned long long GetDiskLengthIoctl(const char *dsk)
{
HANDLE hDisk = CreateFile( dsk,
GENERIC_READ,
FILE_SHARE_VALID_FLAGS,
0,
OPEN_EXISTING,
0,
0);
if(hDisk == INVALID_HANDLE_VALUE)
{
printf("Could not open the disk. GetLastError() returned ", GetLastError());
return 0;
}
GET_LENGTH_INFORMATION gli;
DWORD ret;
DeviceIoControl( hDisk,
IOCTL_DISK_GET_LENGTH_INFO,
0,
0,
&gli,
sizeof(gli),
&ret,
0);
CloseHandle(hDisk);
return gli.Length.QuadPart;
}
int main()
{
const char *Disk = "\\\\.\\PhysicalDrive0"; // or \\\\.\\C:
printf("size = %d (GB)\n", GetDiskLengthIoctl(Disk)/1024/1024/1024);
printf("Lba = %x \n", GetDiskLengthIoctl(Disk)/512);
}