简体   繁体   中英

Reading boot sector of a FAT32 file system

I am writing a program and I need to access some information in the boot sector about the FAT32 file system that I have mounted.

Here is what I did, fully commented.

int main (void) {
    unsigned short *i;                  //2 byte unsigned integer pointer
    char tmp[1024];                     //buffer
    int fd;                             //file descriptor from opening device
    fd =  open("/dev/sdf", O_RDONLY);   //open the device file
    lseek(fd, 14, SEEK_SET);            //set offset to 14 (0x0E), i.e. storing "no. of reserved sectors" of the FAT32 system
    read(fd, tmp, 2);                   //read off 2 bytes, "no. of reserved sectors" is represented by 2 bytes
    i = &tmp;                           //point j at those 2 bytes
    printf("*j: %d\n", *j);             //print *j out
    close(fd);                          //close device
    return 0;
}

The output of *i is 38, which is nonsense. I formatted the file system with mkfs.vfat. I set the "no. of reserved sectors" to 32.

What I have tried:

  • i = (unsigned short *) &tmp, do a casting, this removes the warning when I compile, but doesn't help

  • read(fd, tmp, 512), load the whole boot sector (512 bytes) into tmp, then read from the buffer, but doesn't help, result still 38 though.

  • fiddle with the offset, ie change 14 to 13 or 15, in case I get the index wrong. It prints out 9744 for 13 and 512 for 15 respectively, so doesn't work.

I'm not sure whether I'm doing it the right way. Can someone please point me in the right direction?

Thanks in advance,

Felastine.

Try running:

$ dd if=/dev/sdf of=/tmp/x.bin bs=512 count=1

And then:

$ hd /tmp/x.bin

Or

$ od -tx2 /tmp/x.bin

And post the first lines.

Chances are that your fattools are adding 6 extra reserved sectors of their own. And then they substract them before showing the data.

unsigned short *i;                  //2 byte unsigned integer pointer
char tmp[1024];  
 [...] 
i = &tmp;                           //point j at those 2 bytes

tmp is char[] , &tmp something of order char** . Think again, you don't want the & here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM