How to “read” the MBR (Master Boot Record) in C?

只愿长相守 提交于 2020-01-02 09:12:43

问题


I just want to write a program to analyze MBR in C.

I've known some ways to read it through APIs on Windows or commands on Linux.

But, can I do it in C without any platform-dependent limitation?

If I can't, is there any reason?


回答1:


Reading the master boot record is platform-dependent, the following code for instance works on Windows (if you have the privileges to do it)

#include <windows.h>
#include <stdio.h>
#include <iostream>
using namespace std;
short ReadSect
       (const char *_dsk,    // disk to access
       char *&_buff,         // buffer where sector will be stored
       unsigned int _nsect   // sector number, starting with 0
       )
{
  DWORD dwRead;   
  HANDLE hDisk=CreateFile(_dsk,GENERIC_READ,FILE_SHARE_VALID_FLAGS,0,OPEN_EXISTING,0,0);
  if(hDisk==INVALID_HANDLE_VALUE) // this may happen if another program is already reading from disk
    {  
       CloseHandle(hDisk);
       return 1;
    }
  SetFilePointer(hDisk,_nsect*512,0,FILE_BEGIN); // which sector to read

  ReadFile(hDisk,_buff,512,&dwRead,0);  // read sector
  CloseHandle(hDisk);
  return 0;
}

int main()
{
  char * drv="\\\\.\\C:"; 
  char *dsk="\\\\.\\PhysicalDrive0";
  int sector=0;

  char *buff=new char[512];
  ReadSect(dsk,buff,sector);
  if((unsigned char)buff[510]==0x55 && (unsigned char)buff[511]==0xaa) cout <<"Disk is bootable!"<<endl;


  getchar();

}

http://www.cplusplus.com/forum/windows/18019/

On Linux you can even use a terminal command

sudo dd if=/dev/sda ibs=512 count=1 | hexdump -C

Best solution would be to #ifdef your code and render it platform-dependent.




回答2:


No, reading the MBR is highly platform-dependent - including the question what "the" MBR is if there is more than one hard disk. Best you can hope for is a library that hides the platform-dependent stuff from your code - but you'll probably have to write that yourself.




回答3:


Usually you need to follow platform-specific steps to get a file handle to the whole disk contents, then it's relatively platform-agnostic to use that file to manipulate the MBR.

In addition to needing to identify which hard drive you want, as Guntram mentions, many platforms will require that all filesystems be unmounted from that drive before you can get write access to the disk. This might even preclude your goal.




回答4:


If I can't, is there any reason?

POSIX doesn't have the concept of mounting or block devices (Linux specific), let alone ANSI C.



来源:https://stackoverflow.com/questions/21647752/how-to-read-the-mbr-master-boot-record-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!