Home > front end >  (Windows) Reading the boot sector of disks with C
(Windows) Reading the boot sector of disks with C

Time:05-28

I am trying to read the boot sector of my disk with C. I am planning to modify the code to use it for other disks such as USB flash drives. I tried this code as a test:

#include<stdio.h>
#include<unistd.h>

int main(){
  FILE *fp;
  char buf[512];

  fp = fopen("\\\\.\\PhysicalDrive0", "rb");
  int r = fread(buf, 1, 512, fp);
  printf("Elements read: %s", r);
  sleep(3);
  fclose(fp);
  return 0;
}

When I compile it and run it, I get (literally) Elements read: (null). If I run it as administrator, I instead get Elements read: .

Why am I not able to read the boot sector correctly, and how can I fix the code?

Running on Win10 with MinGW GCC.

CodePudding user response:

First, r is the number of characters read, and you treated it like it was a pointer to a C-style string. To have even a chance of working, you'd need to pass buf, not r, to your printf call, or change %s to %d so you're printing the integer value, not trying to treat it as a pointer to a string. The failed read (when you lack permissions) returns 0, which printf helpfully displays as (null) rather than segfaulting; the successful read returns an integer that when treated as a pointer points to a garbage address that might just barely be readable, but happens to contain nothing but NUL characters, so nothing is printed.

Second, assuming you wanted to see the data, not just get a count of bytes read, odds are the boot sector includes NUL characters early on that will cause the %s scanning to assume the string is already done. If you want to look at the data, either fwrite it to some other file for inspection, or encode it, character by character, as hex and write that to stdout for human reading.

  • Related