这一系列文章是根据cutebunny 的BLOG “windows的磁盘操作” 写成的,主要是部分修改原作中的代码,使之兼容Unicode和Windows 7 64bit. 原文可以在下面的网址找到
http://cutebunny.blog.51cto.com 。 本文是参考 “windows的磁盘操作之三——获取和删除磁盘分区信息”写成。
程序实现了获得当前硬盘分区信息的功能。
// getpart.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "windows.h"
int _tmain(int argc, _TCHAR* argv[])
{
HANDLE hDevice; // handle to the drive to be examined
BOOL result; // results flag
DWORD readed; // discard results
DWORD szNewLayout;
DRIVE_LAYOUT_INFORMATION_EX *dl = NULL;
DWORD i;
// 特别注意 DRIVE_LAYOUT_INFORMATION_EX 结构体的大小,即使只有一个分区,也需要预留出4个分区的大小
// 下面是预留了10个分区的大小。如果直接使用该结构体而不扩大大小会导致 GetLastError =0x7A
szNewLayout=sizeof(DRIVE_LAYOUT_INFORMATION_EX) + 10 * sizeof(PARTITION_INFORMATION_EX);
dl = (DRIVE_LAYOUT_INFORMATION_EX*) new BYTE[szNewLayout];
hDevice = CreateFile(
L"\\\\.\\PhysicalDrive0", // drive to open
GENERIC_READ | GENERIC_WRITE, // access to the drive
FILE_SHARE_READ | FILE_SHARE_WRITE, //share mode
NULL, // default security attributes
OPEN_EXISTING, // disposition
0, // file attributes
NULL // do not copy file attribute
);
if (hDevice == INVALID_HANDLE_VALUE) // cannot open the drive
{
fprintf(stderr, "CreateFile() Error: 0x%X\n", GetLastError());
}
result = DeviceIoControl(
hDevice, // handle to device
IOCTL_DISK_GET_DRIVE_LAYOUT_EX, // dwIoControlCode
NULL, // lpInBuffer
0, // nInBufferSize
dl, // output buffer
szNewLayout, // size of output buffer
&readed, // number of bytes returned
NULL // OVERLAPPED structure
);
if (!result)
{
fprintf(stderr, "IOCTL_DISK_GET_DRIVE_LAYOUT_EX Error: 0x%X\n", GetLastError());
(void)CloseHandle(hDevice);
}
if (dl->PartitionStyle == PARTITION_STYLE_MBR)
{
fprintf(stdout, "It's MBR\n", GetLastError());
}
if (dl->PartitionStyle == PARTITION_STYLE_GPT)
{
fprintf(stdout, "It's GPT\n", GetLastError());
}
if (dl->PartitionStyle == PARTITION_STYLE_RAW)
{
fprintf(stdout, "It's RAW\n", GetLastError());
}
//PartitionCount 这个参数不准确,它给出的是4的整数倍。要想准确,需要结构体中其他的来确定
//
//The number of partitions on the drive. On hard disks with the MBR layout,
//this value will always be a multiple of 4. Any partitions that are actually
//unused will have a partition type of PARTITION_ENTRY_UNUSED (0) set in the PartitionType
//member of the PARTITION_INFORMATION_MBR structure of the Mbr member of the
//PARTITION_INFORMATION_EX structure of the PartitionEntry member of this structure.
fprintf(stdout, "There are %d partitions in PhysicalDrive0\n", dl->PartitionCount);
for (i=0;i<dl->PartitionCount; i++)
{
fprintf(stdout, "Partition[%d] Start Ofs[%llX] Length[%lldMB]\n",
dl->PartitionEntry[i].PartitionNumber,
dl->PartitionEntry[i].StartingOffset,
dl->PartitionEntry[i].PartitionLength.QuadPart / 1024 /1024);
}
delete(dl);
getchar();
return 0;
}
运行结果如下 (注意,运行时需要管理员的权限)

getpart
参考:
1.cutebunny 的BLOG “windows的磁盘操作” 可以在这里下载 WindowsDisk