#include <stdio.h>
#include <windows.h>
#define MAX_DRIVE 10



int main(void)
{
    HANDLE hDrive;
    int i,j;
    char drivename[30];
    unsigned char buf[512*20];
    unsigned char buf2[512*20];
    unsigned long readsize;



    // 物理ドライブ\\.\physicaldrive0から順に読み取る
    for (i=0; i<=MAX_DRIVE; i++){


        sprintf(drivename, "\\\\.\\physicaldrive%d", i);
        hDrive= CreateFile(drivename, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);


        // 認識できるドライブがなければ終了
        if (hDrive == INVALID_HANDLE_VALUE) break;


        printf("Drive%d reading...\n", i);


        // bufに読み込む
        ReadFile(hDrive, buf, sizeof(buf), &readsize, NULL);
        //buf[readsize]= '\0';
		
		int s = *(int *)(buf + 0x1c6);
		
		SetFilePointer(hDrive, s, 0, 0);
		
		ReadFile(hDrive, buf2, sizeof(buf2), &readsize, NULL);

        // ドライブ読み取りハンドルを閉じる
        CloseHandle(hDrive);
		
	
		
		char fname[200];
		sprintf(fname, "mbr%d", i);
		FILE *fp = fopen(fname, "wb");
		fwrite(buf, sizeof(buf), 1, fp);
		fclose(fp);

		sprintf(fname, "mbr%d_1", i);
		fp = fopen(fname, "wb");
		fwrite(buf2, sizeof(buf2), 1, fp);
		fclose(fp);
		
        // １６進ダンプ方式で表示
        for (j=0; j<readsize; j++){
            if (j % 16 == 0) printf("%04X", j);
            printf(" %02X", buf[j]);
            if (j % 16 == 15) putchar('\n');
        }
        putchar('\n');
    }


    return 0; 
}