当前位置: 首页 > 工具软件 > Text_storage > 使用案例 >

2014-06-06:IOCTL_STORAGE_GET_DEVICE_NUMBER获取磁盘信息如磁盘号、磁盘类型、分区号

董小林
2023-12-01
#include <WINDOWS.H>
#include <TCHAR.H>
#include <IOSTREAM.H>

#define DD_TM_DETECTDISKSUCCESS		0
#define DD_TM_LACKPARAMETERERROR	1
#define DD_TM_GETHANDLEFAILERROR	2
#define DD_TM_GETDISKINFOFAILERROR	3

int _tmain(int argc,TCHAR **argv)
{
	if (argc<2)
	{
		return DD_TM_LACKPARAMETERERROR ;
	}
	HANDLE	hDevice = NULL ;
	LPSTR	lpDevicePath = NULL ;
	BOOL	bResult = FALSE;
	STORAGE_DEVICE_NUMBER sdn;
	DWORD	dwReturned = 0 ;

	lpDevicePath = (LPSTR)malloc(sizeof(TCHAR)*261);
	wsprintf(lpDevicePath,TEXT("\\\\.\\PhysicalDrive%d"),argv[1][0]-TEXT('0'));

	cout<<lpDevicePath<<endl;
	hDevice = CreateFile(lpDevicePath,
							GENERIC_READ | GENERIC_WRITE,
							FILE_SHARE_READ | FILE_SHARE_WRITE ,
							NULL,
							OPEN_EXISTING,
							FILE_ATTRIBUTE_NORMAL|FILE_FLAG_OVERLAPPED ,
							hDevice);
	if (hDevice==NULL)
	{
		cout<<"Getting Handle failed!"<<endl;
		return DD_TM_GETHANDLEFAILERROR ;
	}

	bResult = DeviceIoControl(hDevice,
								IOCTL_STORAGE_GET_DEVICE_NUMBER,
								NULL,
								0,
								&sdn,
								sizeof(sdn),
								&dwReturned,
								NULL);		
	if (!bResult)
	{
		cout<<"Getting the info of disk failed!"<<GetLastError()<<endl;
			return DD_TM_GETDISKINFOFAILERROR ;
	}
	cout<<sdn.DeviceNumber<<","<<sdn.DeviceType<<","<<sdn.PartitionNumber<<endl;

	if (hDevice)
	{
		CloseHandle(hDevice);
	}
	if (lpDevicePath)
	{
		free(lpDevicePath);
	}
	return DD_TM_DETECTDISKSUCCESS;							
}
运行结果为:
输入:1
输出:1,7,0
其中的CreateFile的倒数第二个参数可以改为FILE_FLAG_NO_BUFFERING,都差不多。
 类似资料: