|
#include <windows.h>
#include <winioctl.h>
#include <stdio.h>
#include <iostream.h>
LPTSTR ReadMBR(BYTE* pMBR,UINT nLen);
LPTSTR ReadMBR(BYTE* pMBR, UINT nLen)
{
LPTSTR errMSG="";
HANDLE hDevice;
TCHAR szDevicename[64];
LPTSTR szBuff;
DISK_GEOMETRY Geometry;
BOOL bRet;
DWORD bytes,bread,count;
int i;
char *drive = "0";
wsprintf(szDevicename,"\\\\.\\PHYSICALDRIVE%c",*drive);
hDevice = CreateFile(szDevicename,
GENERIC_READ|GENERIC_WRITE,
FILE_SHARE_READ|FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
0,
NULL);
if(hDevice == INVALID_HANDLE_VALUE)
{
errMSG="打开设备出错!";
exit(1);
}
DeviceIoControl(hDevice,FSCTL_LOCK_VOLUME, NULL,0,NULL,0,&count,NULL);
DeviceIoControl(hDevice,IOCTL_DISK_GET_DRIVE_GEOMETRY,NULL,0,&Geometry,sizeof(DISK_GEOMETRY),&count,NULL);
szBuff = (LPSTR)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,Geometry.BytesPerSector);
if ( szBuff == NULL)
{
errMSG="分配内存出错!";
exit(1);
}
bytes = 512;
bRet = ReadFile(hDevice, szBuff, bytes, &bread, NULL);
if (bRet==FALSE || bread<512)
{
errMSG="读MBR出错!";
exit(1);
}
for(int n=0;n<512;n++){
pMBR[n] = szBuff[n];
}
DeviceIoControl(hDevice,FSCTL_UNLOCK_VOLUME, NULL,0,NULL,0,&count,NULL);
CloseHandle(hDevice);
return errMSG;
}
void main()
{
BYTE MBR[512];
ReadMBR(MBR,512);
LPTSTR path="c:\\mbr.dat";
FILE *fp;
if((fp=fopen(path,"wb+"))!=NULL)
{
fwrite(MBR,1,512,fp);
fclose(fp);
printf("已成功读取硬盘MBR,位于mbr.dat\n");
}
else
{
printf("建立文件出错!\n");
}
} |
|