Windows下获取盘符信息
2021-08-30
390
0
在Windows 下,各盘符其实是系统中一个文件,我们了可以通过CreateFile来打开,然后再通过DeviceIoControl函数发送不同的控制码获取相关的信息。
这里的信息包括盘符大小,StartingOffset,DiskNumber,ExtentLength等。
#include<windows.h>
#include<stdio.h>
#include <winioctl.h>
#define IOCTL_VOLUME_BASE ((DWORD) 'V')
#define IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS CTL_CODE(IOCTL_VOLUME_BASE, 0, METHOD_BUFFERED, FILE_ANY_ACCESS)
void Show(char* pName)
{
printf("%s\n",pName);
//char* pName = "\\\\.\\D:";
HANDLE hDevice = CreateFile(pName, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, NULL);
if (hDevice == INVALID_HANDLE_VALUE)
{
return ;
}
typedef struct _DISK_EXTENT {
ULONG DiskNumber;
LARGE_INTEGER StartingOffset;
LARGE_INTEGER ExtentLength;
} DISK_EXTENT, *PDISK_EXTENT;
typedef struct _VOLUME_DISK_EXTENTS {
ULONG NumberOfDiskExtents;
DISK_EXTENT Extents[1];
} VOLUME_DISK_EXTENTS, *PVOLUME_DISK_EXTENTS;
VOLUME_DISK_EXTENTS vde;
ULONG rtn;
BOOL ok= DeviceIoControl(hDevice,
IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS,
NULL,
0,
&vde,
sizeof(vde),
&rtn,
NULL);
if(!ok)
{
DWORD e =GetLastError();
e =e;
}
PDISK_EXTENT pdisk = vde.Extents;
printf("DiskID:%d\n",pdisk->DiskNumber);
printf("NumberOfDiskExtents:%d\n",vde.NumberOfDiskExtents);
printf("start:%I64d\n",pdisk->StartingOffset.QuadPart/512);
printf("ExtentLength:%I64d\n",pdisk->ExtentLength.QuadPart/512);
printf("\n");
CloseHandle(hDevice);
}
void main()
{
DWORD dw=GetLogicalDriveStrings(0,NULL);
LPTSTR lpDriveStrings=(LPTSTR) HeapAlloc( GetProcessHeap(),0,dw*sizeof(TCHAR));
GetLogicalDriveStrings(dw,lpDriveStrings);
for(;strlen(lpDriveStrings);)
{
printf("%s\n",lpDriveStrings);
lpDriveStrings+=strlen(lpDriveStrings);
lpDriveStrings++;
}
Show("\\\\.\\C:");
Show("\\\\.\\D:");
Show("\\\\.\\E:");
Show("\\\\.\\F:");
Show("\\\\.\\G:");
Show("\\\\.\\H:");
Show("\\\\.\\I:");
Show("\\\\.\\M:");
}