[原创]解析mbr得到盘
可能以后编程的日子少了!这个代码是过年家里无网的日子写的!本打算整个工具!但是后面的NTFS解析是参照别人的代码!所以只给我写的得到盘已经盘得大小的代码发一下吧
#include <Windows.h>
#pragma pack(1)
struct DPT
{
char chs[4];
byte type;
char chs1[3];
DWORD dwSpp; //sectors preceding partition
DWORD dwSip; //sectors in partition
};
struct MBR
{
char code[446];
DPT dpt[4];
char sign[2];
};
#pragma pop(1)
class CGetHardDisk
{
public:
BOOL GetDisk();
private:
BOOL TraverDisk(HANDLE hFile,LONGLONG topPosion,LONGLONG uDwSpp);
};
#include "GetHardDisk.h"
BOOL CGetHardDisk::GetDisk()
{
BOOL bResult=FALSE;
HANDLE hFile=INVALID_HANDLE_VALUE;
hFile = CreateFile(TEXT("\\\\.\\PhysicalDrive0"), // drive
GENERIC_READ|GENERIC_WRITE, // no access to the drive
FILE_SHARE_READ | // share mode
FILE_SHARE_WRITE,
NULL, // default security attributes
OPEN_EXISTING, // disposition
0, // file attributes
NULL); // do not copy file attributes
if (hFile == INVALID_HANDLE_VALUE) // cannot open the drive
{
goto Finally;
}
DWORD num;
LONGLONG topExt=0;
MBR mbr={0};
DWORD dwError;
double dG=0;
// Read the first sector (boot sector)
if (!ReadFile(hFile, &mbr, 512, &num, NULL) || num!=512)
{
dwError=GetLastError();
goto Finally;
}
LONGLONG lOffset=0;
LONGLONG utest=0;
int i=0;
LARGE_INTEGER addr;
LONGLONG test=512;
DWORD len;
for (i=0;i<4;i++)
{
if (mbr.dpt[i].type==0xf||mbr.dpt[i].type==5)
{
TraverDisk(hFile,mbr.dpt[1].dwSpp,0);
}
else if (mbr.dpt[i].type==0)
{
continue;
}
else
{
//当前硬盘的大小 以及偏移
utest=mbr.dpt[i].dwSip;
dG=(double)((utest*512)/(1.0*1024*1024*1024));
lOffset=mbr.dpt[i].dwSpp;
}
}
bResult=TRUE;
Finally:
if (hFile!=INVALID_HANDLE_VALUE)
{
CloseHandle(hFile);
}
return bResult;
}
BOOL CGetHardDisk::TraverDisk(HANDLE hFile,LONGLONG topPosion,LONGLONG uDwSpp)
{
BOOL bResult=FALSE;
int i=0;
DWORD num;
LONGLONG lOffset=0;
LONGLONG utest=0;
MBR mbr={0};
double dG=0;
LARGE_INTEGER addr;
DWORD len=0;
addr.QuadPart=(uDwSpp+topPosion)*512;
len = SetFilePointer(hFile,addr.LowPart, &addr.HighPart, FILE_BEGIN);
if (len == (DWORD)-1 && GetLastError() != NO_ERROR)
{
goto Finally;
}
if (!ReadFile(hFile,&mbr,512, &len, NULL))
{
goto Finally;
}
for (i=0;i<4;i++)
{
if (mbr.dpt[i].type==0xf||mbr.dpt[i].type==5)
{
TraverDisk(hFile,topPosion,mbr.dpt[i].dwSpp);
}
else if (mbr.dpt[i].type==0)
{
continue;
}
else
{
//当前硬盘的大小 以及偏移
utest=mbr.dpt[i].dwSip;
dG=(double)((utest*512)/(1.0*1024*1024*1024));
lOffset=uDwSpp+topPosion+mbr.dpt[i].dwSpp;
}
}
bResult=TRUE;
Finally:
return bResult;
}
#include <windows.h>
#include "GetHardDisk.h"
void main()
{
CGetHardDisk getDisk;
getDisk.GetDisk();
}
