这一系列文章是根据cutebunny 的BLOG “windows的磁盘操作” 写成的,主要是部分修改原作中的代码,使之兼容Unicode和Windows 7 64bit. 原文可以在下面的网址找到
http://cutebunny.blog.51cto.com 。 本文是参考 “windows的磁盘操作之四——根据逻辑分区号获得物理磁盘号”写成。实现的功能简单的说就是输入 c: ,程序返回这个
盘符是处于 \\physicalDriveX 上的。
// GetPD.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "windows.h" /****************************************************************************** * Function: get disk's physical number from its drive letter * e.g. C-->0 (C: is on disk0) * input: letter, drive letter * output: N/A * return: Succeed, disk number * Fail, -1 ******************************************************************************/ DWORD GetPhysicalDriveFromPartitionLetter(TCHAR letter) { HANDLE hDevice; // handle to the drive to be examined BOOL result; // results flag DWORD readed; // discard results STORAGE_DEVICE_NUMBER number; //use this to get disk numbers TCHAR path[MAX_PATH]; wsprintf(path, L"\\\\.\\%c:", letter); hDevice = CreateFile(path, // 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: %ld\n", GetLastError()); return DWORD(-1); } result = DeviceIoControl( hDevice, // handle to device IOCTL_STORAGE_GET_DEVICE_NUMBER, // dwIoControlCode NULL, // lpInBuffer 0, // nInBufferSize &number, // output buffer sizeof(number), // size of output buffer &readed, // number of bytes returned NULL // OVERLAPPED structure ); if (!result) // fail { fprintf(stderr, "IOCTL_STORAGE_GET_DEVICE_NUMBER Error: %ld\n", GetLastError()); (void)CloseHandle(hDevice); return (DWORD)-1; } printf("%d %d %d\n\n", number.DeviceType, number.DeviceNumber, number.PartitionNumber); (void)CloseHandle(hDevice); return number.DeviceNumber; } int _tmain(int argc, _TCHAR* argv[]) { GetPhysicalDriveFromPartitionLetter('c'); getchar(); return 0; }
运行结果如下 (注意,运行时需要管理员的权限)
其中的 7 是 FILE_DEVICE_DISK, 0 表示 PhysicalDrive0 ,2 表示这个硬盘上有2个分区。
参考:
1.cutebunny 的BLOG “windows的磁盘操作” 可以在这里下载 WindowsDisk
2.http://msdn.microsoft.com/en-us/library/windows/desktop/bb968800(v=vs.85).aspx IOCTL_STORAGE_GET_DEVICE_NUMBER control code
3.http://msdn.microsoft.com/en-us/library/windows/desktop/bb968801(v=vs.85).aspx STORAGE_DEVICE_NUMBER structure