user3731622
user3731622

Reputation: 5095

C++ method for Diskpart list disk

If I run diskpart and give it the command list disk, then it shows me a table like

Disk ###  Status         Size     Free     Dyn  Gpt 
--------  -------------  -------  -------  ---  ---

Disk 0    Online          100 GB      0 B           
Disk 1    Online         3000 GB      0 B        *  
Disk 2    No Media           0 B      0 B           
Disk 3    Foreign         500 GB   490 GB   *         
Disk 4    No Media           0 B      0 B           

How can I obtain obtain such a list using C++?

Upvotes: 0

Views: 1806

Answers (2)

ko-barry
ko-barry

Reputation: 11

You can use the following command to get all drives in drives.txt.

wmic diskdrive get * > drives.txt

In the drives.txt, you can get the Caption, Index, DeviceID, and Size of drives.

Use the following command to get all partions of drives in partitions.txt.

wmic partition get * > partitions.txt

In the partitions.txt, you can get the Caption as "Disk #0, Partition #0" and Description like "GPT: Basic Data".

To obtain the result like above using C++, take a look at https://learn.microsoft.com/en-us/windows/win32/wmisdk/example--getting-wmi-data-from-the-local-computer .

Get drives informaton by "SELECT * FROM Win32_DiskDrive" and get partitions by "SELECT * FROM Win32_DiskPartition" .

Upvotes: 0

JAtkins
JAtkins

Reputation: 1

I use this method:

  1. Get a list of disks using GetLogicalDriveStrings(). You can filter for removable or fixed disks with this call.

  2. Get a handle to each Volume using something like the following.

    HANDLE hVolume = CreateFile(volumeName, access, FILE_SHARE_READ |    FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
  3. Get the Disk Number using the volume handle. I cant remember if you need to lock/unmount the volume for this next bit but those are well documented and easy to do now that you have the volume handle.

    
        STORAGE_DEVICE_NUMBER sdn;
        DWORD dwBytesReturned = 0;
        if (!DeviceIoControl(hVolume, IOCTL_STORAGE_GET_DEVICE_NUMBER, NULL, 0, &sdn, sizeof(sdn), &dwBytesReturned, NULL)){
    
    
    }
    
    return sdn.DeviceNumber;
    

Upvotes: 0

Related Questions