1. 程式人生 > >讀取硬碟的第一扇區資料(MBR+DPT+Signature)

讀取硬碟的第一扇區資料(MBR+DPT+Signature)

/*********************************************************
* FileName: DiskInfo.cpp
* Author  : intret
* Data    : 2009-5-21 12:33 PM
*********************************************************/
#include <iostream>
#include <iomanip>
#include <tchar.h>
#include <Windows.h>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
    HANDLE hDevice = CreateFile(_T("////.//PHYSICALDRIVE0"), GENERIC_READ|GENERIC_WRITE,
        FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,OPEN_EXISTING,0,NULL);
    if ( hDevice != INVALID_HANDLE_VALUE)
    {
        int count=0;
        unsigned
char buffer[512]; //主引導扇區資料(446B+ 64B+ 2B = MBR+DPT+Signature)
        DWORD NumberOfBytesRead;
        //讀取資料到緩衝區
        BOOL ret = ReadFile(hDevice, buffer, sizeof(buffer), &NumberOfBytesRead, NULL);
        if (ret)
        {
            cout<<"The data of MBR(416), DPT(64) and Signature(2) is:"
<<endl<<endl;
            cout<<setiosflags(ios::uppercase);      //大寫顯示
            for (int i=0; i<512; i++)       //前446bytes是MBR
            {
                cout<<hex<<setw(2)<<setfill('0')<<buffer[i]+0;
                if (((i+1)%16) )
                    cout<<ends;
                else
                    cout<<endl;
                if (!((i+1)%256))
                    cout<<endl;
            }
            cout<<endl;
        }
        else
        {
            cout<<"Failed to read data of xx"<<endl;
        }
        CloseHandle(hDevice);
    }
    else
    {
        cout<<"開啟物理驅動器失敗!"<<endl;
    }
    return 0;
}