I am trying to build my own C program that basically works just like fdisk vdisk ‘p’ command. I just want to be able to read in the first 512 bytes of the disk, lseek to the start of the partitions at (0x1BE) and then read the partition type, name, size, ect. I am unsure how to actually read these values. I have used the read() linux function to read in 512 bytes but when I try displaying/viewing them in any way, nothing is shown. What am I doing wrong?
int main(int argc, char *argv[]) {
int bytes_read;
char mbr[512];
int file;
if(argc == 1) {
// Print some help info
printf ("Here is some help info: \n\n");
} else if(argc < 3) {
printf("File: %s\n\n", argv[1]);
file = open(argv[1], O_RDONLY);
lseek(bytes_read, 0, 0);
//First get the MBR
bytes_read = read(file, mbr, 512);
printf("MBR=%s\n\nbytes_read=%d\n\n", mbr, bytes_read);
} else {
printf ("Incorrect usage: fdisk <disk>\n\n");
}
}
Don’t try to use
printfwith binary data. If your binary data starts with aNUL(ASCII 0), then printf will assume you’ve got an empty string. You can usewrite()to write out arbitrary data (it takes a buffer and length), e.g:…but even this won’t necessarily display anything useful, because your terminal may try to interpret control characters in the output. You’re best bet would then be to pipe the output to something like
xxdorod, both of which will produce a hexdump of their input data.For example, the first 512 bytes of my local drive are all
NUL. Usingwrite()in your code (and removing thatlseek) results in 512NULbytes on output. Try passing something other than disk to your code, e.g.:The structure of a standard DOS MBR is documented here, suggesting that you might start with data structures like this:
And populate it something like this: