Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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.

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top