windows的磁盘操作之五——获取物理磁盘上的所有逻辑分区号
本节讨论与上一节相反的操作,根据物理驱动器号获取该磁盘上的所有分区号。DeviceIoControl函数并没有提供操作码来直接完成此操作,所以需要稍微绕个圈子来实现这项功能。
大体思路为,先通过GetLogicalDrives函数获得系统中所有分区号,然后过滤掉非硬盘分区(例如软驱、光驱),再过滤掉不属于指定物理磁盘的分区,最后剩下的就是我们所需要的分区号了。
代码如下
/******************************************************************************
* Function: get disk's drive letters from physical number
* e.g. 0-->{C, D, E} (disk0 has 3 drives, C:, D: and E:)
* input: phyDriveNumber, disk's physical number
* output: letters, letters array
* return: Succeed, the amount of letters
* Fail, -1
******************************************************************************/
DWORD GetPartitionLetterFromPhysicalDrive(DWORD phyDriveNumber, CHAR **letters)
{
DWORD mask;
DWORD driveType;
DWORD bmLetters;
DWORD diskNumber;
CHAR path[DISK_PATH_LEN];
CHAR letter;
DWORD letterNum;
WORD i;
CHAR *p;
bmLetters = GetLogicalDrives();
if (0 == bmLetters)
{
return (DWORD)-1;
}
letterNum = 0;
for (i = 0; i < sizeof(DWORD) * 8; i++)
{
mask = 0x1u << i;
if ((mask & bmLetters) == 0) //get one letter
{
continue;
}
letter = (CHAR)(0x41 + i); //ASCII change
sprintf(path, "%c:\\", letter);
driveType = GetDriveType(path);
if (driveType != DRIVE_FIXED)
{
bmLetters &= ~mask; //clear this bit
continue;
}
diskNumber = GetPhysicalDriveFromPartitionLetter(letter);
if (diskNumber != phyDriveNumber)
{
bmLetters &= ~mask; //clear this bit
continue;
}
letterNum++;
}
//build the result
*letters = (CHAR *)malloc(letterNum);
if (NULL == *letters)
{
return (DWORD)-1;
}
p = *letters;
for (i = 0; i < sizeof(DWORD) * 8; i++)
- 发表评论
-
- 最新评论 更多>>