Read MBR via ReadFile function

View Code
 1 // ReadMBR.cpp : Defines the entry point for the console application.
2 //
3
4 #include "stdafx.h"
5 const UINT uSectorSize=512; //扇区大小(byte)
6 const UINT uBegSector=0;//扇区编号
7 const UINT uSectorNum=1;//扇区数量
8 const UINT uReadSize=uSectorNum*uSectorSize;//读取数据大小
9 BYTE bBuffer[uReadSize]={0};
10 BYTE rBuffer[uReadSize]={0};
11 const char drive[]="\\\\.\\PHYSICALDRIVE0";
12
13 void ShowByteInform(PBYTE,UINT);
14 int main(int argc, char* argv[])
15 {
16 WNDCLASS wc;
17
18 HANDLE hDeviceHandle;
19 HICON mIcon;
20 mIcon=LoadIcon(NULL,IDI_WARNING);
21 wc.hIcon=mIcon;
22 hDeviceHandle=CreateFile(drive,GENERIC_WRITE|GENERIC_READ,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_EXISTING,0,0);
23 if(hDeviceHandle==INVALID_HANDLE_VALUE)
24 {
25 printf("open disk error!!\n");
26 return 0;
27 }
28
29 SetFilePointer(hDeviceHandle,uBegSector*uSectorSize,0,FILE_BEGIN);
30 DWORD dwReadByte;
31 if(ReadFile(hDeviceHandle,(LPVOID)bBuffer,uReadSize,&dwReadByte,NULL)==0)
32 {
33 printf("Read Error!\n");
34 DWORD dw=GetLastError();
35 }//读入bBuffer
36 else
37 bBuffer[446]==0x80?bBuffer[446]=0x00:bBuffer[446]=0x80;
38 SetFilePointer(hDeviceHandle,uBegSector*uSectorSize,0,FILE_BEGIN);
39 if(WriteFile(hDeviceHandle,(LPVOID)bBuffer,uReadSize,&dwReadByte,NULL))
40 {
41 printf("Write disk Succeed!\n");
42 }else
43 {
44 printf("Write disk failed heihei!\n");
45 }
46
47 if(dwReadByte==0)
48 {
49 printf("open disk 0 error!!\n");
50 }
51 FILE *fp;
52 if((fp=fopen("C:\\BOOT.dat","wb"))!=NULL)
53 fwrite(bBuffer,sizeof(BYTE),sizeof(bBuffer),fp);
54 else
55 printf("create file failed!\n");
56 fclose(fp);
57 if((fp=fopen("C:\\BOOT.dat","rb"))!=NULL)
58 fread(rBuffer,1,sizeof(rBuffer),fp);
59 fclose(fp);
60
61 ShowByteInform(bBuffer,uReadSize);
62 getchar();
63 return 0;
64 }
65 void ShowByteInform(PBYTE pBuf,UINT uSize)
66 {
67 for(UINT i=1;i<=uSize;i++)
68 {
69 printf("%02X",pBuf[i-1]);
70 if(i%16==0)
71 putchar('\n');
72 else if(i%8==0)
73 printf(" ");
74 }
75 }
posted @ 2011-12-13 09:53  soderman  阅读(272)  评论(0编辑  收藏  举报