Advertisement
andruhovski

DeviceIoControl Demo

Mar 11th, 2013
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.19 KB | None | 0 0
  1. #include <windows.h>
  2. #include <winioctl.h>
  3. #include <stdio.h>
  4.  
  5. BOOL GetDriveGeometry(DISK_GEOMETRY *pdg)
  6. {
  7.   HANDLE hDevice;               // handle to the drive to be examined
  8.   BOOL bResult;                 // results flag
  9.   DWORD junk;                   // discard results
  10.  
  11.   hDevice = CreateFile("\\\\.\\PhysicalDrive0",  // drive to open
  12.                     0,                // no access to the drive
  13.                     FILE_SHARE_READ | // share mode
  14.                     FILE_SHARE_WRITE,
  15.                     NULL,             // default security attributes
  16.                     OPEN_EXISTING,    // disposition
  17.                     0,                // file attributes
  18.                     NULL);            // do not copy file attributes
  19.  
  20.   if (hDevice == INVALID_HANDLE_VALUE) // cannot open the drive
  21.   {
  22.     return (FALSE);
  23.   }
  24.  
  25.   bResult = DeviceIoControl(hDevice,  // device to be queried
  26.       IOCTL_DISK_GET_DRIVE_GEOMETRY,  // operation to perform
  27.                              NULL, 0, // no input buffer
  28.                             pdg, sizeof(*pdg),     // output buffer
  29.                             &junk,                 // # bytes returned
  30.                             (LPOVERLAPPED) NULL);  // synchronous I/O
  31.  
  32.   CloseHandle(hDevice);
  33.  
  34.   return (bResult);
  35. }
  36.  
  37. int main(int argc, char *argv[])
  38. {
  39.   DISK_GEOMETRY pdg;            // disk drive geometry structure
  40.   BOOL bResult;                 // generic results flag
  41.   ULONGLONG DiskSize;           // size of the drive, in bytes
  42.  
  43.   bResult = GetDriveGeometry (&pdg);
  44.  
  45.   if (bResult)
  46.   {
  47.     printf("Cylinders = %I64d\n", pdg.Cylinders);
  48.     printf("Tracks per cylinder = %ld\n", (ULONG) pdg.TracksPerCylinder);
  49.     printf("Sectors per track = %ld\n", (ULONG) pdg.SectorsPerTrack);
  50.     printf("Bytes per sector = %ld\n", (ULONG) pdg.BytesPerSector);
  51.  
  52.     DiskSize = pdg.Cylinders.QuadPart * (ULONG)pdg.TracksPerCylinder *
  53.       (ULONG)pdg.SectorsPerTrack * (ULONG)pdg.BytesPerSector;
  54.     printf("Disk size = %I64d (Bytes) = %I64d (Gb)\n", DiskSize,
  55.            DiskSize / (1024 * 1024 * 1024));
  56.   }
  57.   else
  58.   {
  59.     printf ("GetDriveGeometry failed. Error %ld.\n", GetLastError ());
  60.   }
  61.  
  62.   return ((int)bResult);
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement