How to find the Disk partition style using IOCTL?

Gopika Lakshmi 0 Reputation points
2025-01-16T07:18:06.24+00:00

I am trying to find the disk partition style using IOCTL. Earlier, I was using WMI, but in this particular code, I need to provide the physical drive path. What should be given as input, and how can I find or determine which physical drive path to provide? Also, is there a need to use IOCTL, or is WMI a better approach? Which method is recommended?

#include <windows.h>

#include <winioctl.h>

#include <iostream>

void GetDiskPartitionStyle(int& m_DiskPartitionStyle, const std::wstring& physicalDrivePath)

{

// Initialize the partition style as MBR

m_DiskPartitionStyle = HardDiskPartitionType_MBR;

// Open the physical drive

HANDLE hDevice = CreateFile(

    physicalDrivePath.c_str(), 

    GENERIC_READ,

    FILE_SHARE_READ | FILE_SHARE_WRITE,

    NULL,

    OPEN_EXISTING,

    0,

    NULL);

if (hDevice == INVALID_HANDLE_VALUE) {

    std::wcerr << L"Failed to open device. Error: " << GetLastError() << std::endl;

    return;

}

// Get partition information

PARTITION_INFORMATION_EX partitionInfo = { 0 };

DWORD bytesReturned;

if (DeviceIoControl(

        hDevice,

        IOCTL_DISK_GET_PARTITION_INFO_EX,

        NULL,

        0,

        &partitionInfo,

        sizeof(partitionInfo),

        &bytesReturned,

        NULL))

{

    // Check the partition style

    if (partitionInfo.PartitionStyle == PARTITION_STYLE_GPT) {

        m_DiskPartitionStyle = HardDiskPartitionType_GPT;

    }

} else {

    std::wcerr << L"DeviceIoControl failed. Error: " << GetLastError() << std::endl;

}

// Close the handle

CloseHandle(hDevice);
```}

  
any better approach?
C++
C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,829 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. RLWA32 46,461 Reputation points
    2025-01-16T09:23:33.74+00:00

    You can determine whether a partition is GPT or MBR by using DeviceIoControl with a handle to the volume. For example, to determine the type of partition on drive F: you could pass "\\.\F:" to CreateFile (don't forget to use double backslashes for C/C++ string literals).

    Also, see How do I get from a volume to the physical disk that holds it?.

    BTW, you can also pass a handle to the physical disk to DeviceIoControl and request IOCTL_DISK_GET_DRIVE_LAYOUT_EX which returns DRIVE_LAYOUT_INFORMATION_EX.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.