Skip to content

Instantly share code, notes, and snippets.

@thomasalvatran
Last active Jan 28, 2022
Embed
What would you like to do?
Read Master Boot Record(MBR) from the disk (USB, Hard Drive, SSD, SD card)
//Check img whether there is partition in MBR locates at 0x1BE of 1st sector
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE * in = fopen("test.img", "rb"); //change img to your img
// FILE * in = fopen("usb.img", "rb");
unsigned int i, start_sector, length_sectors;
fseek(in, 0x1BE, SEEK_SET); // go to partition table start
for(i=0; i<4; i++) { // read all four entries
printf("Partition entry %d: First byte %02X\n", i, fgetc(in));
printf(" Partition start in CHS: %02X:%02X:%02X\n", fgetc(in), fgetc(in), fgetc(in));
printf(" Partition type 0x%02X\n", fgetc(in));
printf(" Partition end in CHS: %02X:%02X:%02X\n", fgetc(in), fgetc(in), fgetc(in));
fread(&start_sector, 4, 1, in);
fread(&length_sectors, 4, 1, in);
printf(" Relative LBA address 0x%08X, %d sectors long\n", start_sector, length_sectors);
}
fclose(in);
return 0;
}
@thomasalvatran
Copy link
Author

thomasalvatran commented Feb 9, 2018

~/Ctest/k_r/kernel_hi11Bulk$ gcc read_mbr.c -o read_mbr
~/Ctest/k_r/kernel_hi11Bulk$ sudo ./read_mbr
Partition entry 0: First byte 00
Partition start in CHS: 00:04:02
Partition type 0x06
Partition end in CHS: C9:E4:04
Relative LBA address 0x00000081, 1953663 sectors long
Partition entry 1: First byte 00
Partition start in CHS: 00:00:00
Partition type 0x00
Partition end in CHS: 00:00:00
Relative LBA address 0x00000000, 0 sectors long
Partition entry 2: First byte 00
Partition start in CHS: 00:00:00
Partition type 0x00
Partition end in CHS: 00:00:00
Relative LBA address 0x00000000, 0 sectors long
Partition entry 3: First byte 00
Partition start in CHS: 00:00:00
Partition type 0x00
Partition end in CHS: 00:00:00
Relative LBA address 0x00000000, 0 sectors long
~/Ctest/k_r/kernel_hi11Bulk$

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment