Sunday, July 24, 2022

CPP: Windows: DeviceIoControl

CPP: Windows: DeviceIoControl

An application can use the DeviceIoControl function to perform direct input and output operations on, or retrieve information about, a floppy disk drive, hard disk drive, tape drive, or CD-ROM drive.

The following example demonstrates how to retrieve information about the first physical drive in the system. It uses the CreateFile function to retrieve the device handle to the first physical drive, and then uses DeviceIoControl with the IOCTL_DISK_GET_DRIVE_GEOMETRY control code to fill a DISK_GEOMETRY structure with information about the drive.
#include <windows.h>
#include <winioctl.h>
#include <stdio.h>
LPCWSTR wszDrive = L"\\\\.\\PhysicalDrive0";
BOOL GetDriveGeometryInfo(LPCWSTR wszPath, DISK_GEOMETRY* pdg)
{
HANDLE hDevice = INVALID_HANDLE_VALUE;
BOOL bResult = FALSE;
DWORD junk = 0;
hDevice = CreateFileW(wszPath,
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,
(LPOVERLAPPED)NULL);
CloseHandle(hDevice);
return (bResult);
}
int wmain(int argc, wchar_t* argv[])
{
DISK_GEOMETRY pdg = { 0 };
BOOL bResult = FALSE;
ULONGLONG DiskSize = 0;
bResult = GetDriveGeometryInfo(wszDrive, &pdg);
if (bResult)
{
wprintf(L"Drive path = %ws\n", wszDrive);
wprintf(L"Cylinders = %I64d\n", pdg.Cylinders.QuadPart);
wprintf(L"Tracks/cylinder = %ld\n", (ULONG)pdg.TracksPerCylinder);
wprintf(L"Sectors/track = %ld\n", (ULONG)pdg.SectorsPerTrack);
wprintf(L"Bytes/sector = %ld\n", (ULONG)pdg.BytesPerSector);
DiskSize = pdg.Cylinders.QuadPart * (ULONG)pdg.TracksPerCylinder *
(ULONG)pdg.SectorsPerTrack * (ULONG)pdg.BytesPerSector;
wprintf(L"Disk size = %I64d (Bytes)\n"
L" = %.2f (Gb)\n",
DiskSize, (double)DiskSize / (1024 * 1024 * 1024));
}
else
{
wprintf(L"GetDriveGeometry failed. Error %ld.\n", GetLastError());
}
return ((int)bResult);
}

Notes:
- Tested using Visual Studio 2022 (17.2.6) C++ Windows Console template
Reference(s):
https://docs.microsoft.com/en-us/windows/win32/devio/calling-deviceiocontrol

No comments:

Fedora install screen chronicle

Fedora install screen chronicle Below are links to Fedora installation screens. It is interesting to see how it has evolved over time. Fe...