windows cplusplus 获取磁盘分区信息
时间: 2023-10-01 12:05:55 浏览: 95
可以使用Windows API函数来获取磁盘分区信息,以下是示例代码:
```C++
#include <iostream>
#include <windows.h>
#include <winioctl.h>
using namespace std;
int main()
{
char drive[] = "\\\\.\\PhysicalDrive0"; // 磁盘编号,0为第一个物理磁盘
HANDLE hDisk = CreateFileA(drive, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
if (hDisk == INVALID_HANDLE_VALUE)
{
cout << "Failed to open disk!" << endl;
return 0;
}
STORAGE_PROPERTY_QUERY query;
char buf[1024];
memset(&query, 0, sizeof(query));
memset(buf, 0, sizeof(buf));
query.PropertyId = StorageDeviceProperty;
query.QueryType = PropertyStandardQuery;
if (!DeviceIoControl(hDisk, IOCTL_STORAGE_QUERY_PROPERTY, &query, sizeof(query), buf, sizeof(buf), NULL, NULL))
{
cout << "Failed to get disk property!" << endl;
CloseHandle(hDisk);
return 0;
}
STORAGE_DEVICE_DESCRIPTOR* desc = (STORAGE_DEVICE_DESCRIPTOR*)buf;
char* vendor = (char*)buf + desc->VendorIdOffset;
char* product = (char*)buf + desc->ProductIdOffset;
char* serial = (char*)buf + desc->SerialNumberOffset;
cout << "Vendor: " << vendor << endl;
cout << "Product: " << product << endl;
cout << "Serial Number: " << serial << endl;
CloseHandle(hDisk);
return 0;
}
```
该代码通过调用`CreateFile`函数打开磁盘设备,然后使用`DeviceIoControl`函数发送`IOCTL_STORAGE_QUERY_PROPERTY`命令获取设备属性,最后解析设备属性信息并输出到控制台上。
阅读全文