如何解决查找分区的起始偏移量
假设我有一个带有两个分区e:,f:的USB驱动器。我怎么知道分区e:或f:从哪个偏移量开始,以便我可以从该偏移量开始写入原始数据。我找不到任何可以为我提供c ++偏移量的函数。在Dos中,我可以轻松地通过wmic partition get Index,Name,StartingOffset
来实现这一点。
解决方法
要获取物理驱动器中的StartingOffset
个分区(例如\\\\.\\PhysicalDrive1
),可以使用IOCTL_DISK_GET_DRIVE_LAYOUT_EX
获取每个分区的PARTITION_INFORMATION_EX
阵列:
#include <windows.h>
#include <stdio.h>
#define wszDrive L"\\\\.\\PhysicalDrive1"
int wmain(int argc,wchar_t* argv[])
{
HANDLE hDevice = INVALID_HANDLE_VALUE; // handle to the drive to be examined
BOOL bResult = FALSE; // results flag
DWORD junk = 0; // discard results
DWORD error;
DWORD szNewLayout = sizeof(DRIVE_LAYOUT_INFORMATION_EX) + sizeof(PARTITION_INFORMATION_EX) * 4 * 25;
hDevice = CreateFileW(wszDrive,// drive to open
GENERIC_READ,// no access to the drive
FILE_SHARE_READ,NULL,// default security attributes
OPEN_EXISTING,// disposition
0,// file attributes
0); // do not copy file attributes
if (hDevice == INVALID_HANDLE_VALUE) // cannot open the drive
{
error = GetLastError();
printf("CreateFileW error: %d\n",error);
return -1;
}
DRIVE_LAYOUT_INFORMATION_EX* pdg = (DRIVE_LAYOUT_INFORMATION_EX*)malloc(szNewLayout);
if (pdg == NULL)
{
error = GetLastError();
printf("malloc error: %d\n",error);
CloseHandle(hDevice);
return -1;
}
ZeroMemory(pdg,szNewLayout);
bResult = DeviceIoControl(hDevice,// device to be queried
IOCTL_DISK_GET_DRIVE_LAYOUT_EX,// operation to perform
NULL,// no input buffer
pdg,szNewLayout,// sizeof(*pdg)*2,// output buffer
&junk,// # bytes returned
(LPOVERLAPPED)NULL); // synchronous I/O
if (!bResult)
{
error = GetLastError();
printf("DeviceIoControl error: %d\n",error);
free(pdg);
CloseHandle(hDevice);
return -1;
}
for (int i = 0; i < pdg->PartitionCount; i++) {
printf("partition %d: %lld\n",i,pdg->PartitionEntry[i].StartingOffset.QuadPart);
}
free(pdg);
CloseHandle(hDevice);
return 0;
}
要获取指定分区(例如StartingOffset
)的\\\\.\\E:
,可以使用IOCTL_DISK_GET_PARTITION_INFO_EX
:
#include <windows.h>
#include <stdio.h>
#define wszDrive L"\\\\.\\E:"
int wmain(int argc,wchar_t* argv[])
{
HANDLE hDevice = INVALID_HANDLE_VALUE; // handle to the drive to be examined
BOOL bResult = FALSE; // results flag
DWORD junk = 0; // discard results
DWORD error;
PARTITION_INFORMATION_EX piex;
ZeroMemory(&piex,sizeof(PARTITION_INFORMATION_EX));
hDevice = CreateFileW(wszDrive,error);
return -1;
}
bResult = DeviceIoControl(hDevice,IOCTL_DISK_GET_PARTITION_INFO_EX,&piex,sizeof(PARTITION_INFORMATION_EX),&junk,(LPOVERLAPPED)NULL);
if (!bResult)
{
error = GetLastError();
printf("DeviceIoControl error: %d\n",error);
CloseHandle(hDevice);
return -1;
}
wprintf(L"%s StartingOffset: %lld\n",wszDrive,piex.StartingOffset.QuadPart);
CloseHandle(hDevice);
return 0;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。