Visual c++ example to read mbr

Install windows ddk and run it using admin permission, otherwise all bytes that read from mbr are 0xcd. It can be compile using visual c++ community exition.

virus

#include "stdafx.h"
#include <cstdlib>
#include <windows.h>
#include <stdio.h>
#include <iostream>
#define FILE_SHARE_VALID_FLAGS (0x00000007) 
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;
	wchar_t wdsk[100];
	size_t count;
	mbstowcs_s(&count, wdsk, sizeof(wdsk) / sizeof(wdsk[0]), _dsk, _TRUNCATE);
	HANDLE hDisk = CreateFile(wdsk, 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 *dsk = "\\\\.\\PhysicalDrive0";
	int sector = 0;

	char *buff = new char[512];
	ReadSect(dsk, buff, sector);
	for (int x = 0; x < 512; x++) {
		printf("%x ", buff[x] & 0xff);
	}
	if ((unsigned char)buff[510] == 0x55 && (unsigned char)buff[511] == 0xaa) {
		cout << "Disk is bootable!" << endl;
	}

	getchar();
	return 0;
}

read count : 74