#include <windows.h>
#include <stdio.h>
BOOL GetDriveGeometry(DISK_GEOMETRY* dg)
{
HANDLE hDevice; // handle to the drive
BOOL bResult;
DWORD bytesreturned;
/*
HANDLE CreateFileA(
[in] LPCSTR lpFileName,
[in] DWORD dwDesiredAccess,
[in] DWORD dwShareMode,
[in, optional] LPSECURITY_ATTRIBUTES lpSecurityAttributes,
[in] DWORD dwCreationDisposition,
[in] DWORD dwFlagsAndAttributes,
[in, optional] HANDLE hTemplateFile
);
*/
hDevice = CreateFile(L"\\\\.\\PhysicalDrive0", // drive to open
0,
FILE_SHARE_READ |
FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING, // disposition
0,
NULL);
if (hDevice == INVALID_HANDLE_VALUE) // cannot open the drive
{
return (FALSE);
}
/*
BOOL DeviceIoControl(
[in] HANDLE hDevice,
[in] DWORD dwIoControlCode,
[in, optional] LPVOID lpInBuffer,
[in] DWORD nInBufferSize,
[out, optional] LPVOID lpOutBuffer,
[in] DWORD nOutBufferSize,
[out, optional] LPDWORD lpBytesReturned,
[in, out, optional] LPOVERLAPPED lpOverlapped
);
*/
bResult = DeviceIoControl(hDevice,
IOCTL_DISK_GET_DRIVE_GEOMETRY,
NULL, 0,
dg, sizeof(*dg), // output buffer - DISK_GEOMETRY
&bytesreturned,
(LPOVERLAPPED)NULL);
CloseHandle(hDevice);
return (bResult);
}
int main(int argc, char* argv[])
{
/*
typedef struct _DISK_GEOMETRY {
LARGE_INTEGER Cylinders;
MEDIA_TYPE MediaType;
DWORD TracksPerCylinder;
DWORD SectorsPerTrack;
DWORD BytesPerSector;
} DISK_GEOMETRY, *PDISK_GEOMETRY;
*/
DISK_GEOMETRY dg; // drive geometry structure
BOOL bResult;
bResult = GetDriveGeometry(&dg);
if (bResult)
{
//printf("Cylinders = %I64d\n", pdg.Cylinders);
printf("Cylinders = %lld\n", dg.Cylinders);
printf("Tracks per cylinder = %ld\n", (ULONG)dg.TracksPerCylinder);
printf("Sectors per track = %ld\n", (ULONG)dg.SectorsPerTrack);
printf("Bytes per sector = %ld\n", (ULONG)dg.BytesPerSector);
ULONGLONG DiskSize = dg.Cylinders.QuadPart * (ULONG)dg.TracksPerCylinder *
(ULONG)dg.SectorsPerTrack * (ULONG)dg.BytesPerSector; // in bytes
printf("Disk size = %I64d(Bytes) = %I64d(GB)\n", DiskSize, DiskSize / (1024 * 1024 * 1024));
}
else
{
printf("GetDriveGeometry Error: %ld.\n", GetLastError());
}
return ((int)bResult);
}
/*
run:
Cylinders = 121601
Tracks per cylinder = 255
Sectors per track = 63
Bytes per sector = 512
Disk size = 1000202273280(Bytes) = 931(GB)
*/