How can I find the first clusters/blocks of a file?

1.2k Views Asked by At

I have a FAT16 drive that contains the following info: enter image description here Bytes per sector: 512 bytes (0x200)

Sectors per cluster: 64 (0x40)

Reserved sectors: 6 (0x06)

Number of FATs: 2 (0x02)

Number of root entries: 512 (0x0200)

Total number of sectors: 3805043 (0x3a0f73)

Sectors per file allocation table: 233 (0xE9)

Root directory is located at sector 472 (0x1d8) enter image description here

I'm looking for a file with the following details:

File name: LOREMI~1

File extension: TXT

File size: 3284 bytes (0x0cd4)

First cluster: 660 (0x294)

However, I would admit that the start of the file cluster is located at sector 42616. My problem is that what equation should I use that would produce 42616? enter image description here

I have trouble figuring this out since there is barely any information about this other than a tutorial made by Tavi Systems but the part involving this is very hard to follow.

1

There are 1 best solutions below

0
NHI7864 On

Actually, the FAT filesystem is fairly well documented. The official FAT documentation by Microsoft can be found by the filename fatgen103.

The directory entry LOREMI~1.TXT can be found in the root directory and is precedented by the long file name entry (xt, lorem ipsum.tlorem ipsum.txt), the directory entry is documented in the «FAT Directory Structure» chapter; in case of FAT16 you are interested in the 26th to 28th byte to get the cluster address (DIR_FstClusLo), which is (little endian!) 0x0294 (or 660₁₀).

Based on the BPB header information you provided we can calculate the the data sector like this:

data_sector = (cluster-2) * sectors_per_cluster + 
              (reserved_sectors + (number_of_fats * fat_size) +
               first_data_sector)

Why cluster-2? Because the first two clusters in a FAT filesystem are always reserved for the BPB header block as well as the FAT itself, see chapter «FAT Data Structure» in fatgen103.doc.

In order for us to solve this, we still need to determine the sector span of the root directory entry. For FAT12/16 this can be determined like this:

first_data_sector = ((root_entries * directory_entry_size) +
                     (bytes_per_sector - 1)) // bytes_per_sector

The directory entry size is always 32 bytes as per specification (see chapter «FAT Directory Structure» in fatgen103.doc), every other value is known by now:

first_data_sector = ((512*32)+(512-1)) // 512 → 32
data_sector = (660-2)*64+(6+(2*233)+32) → 42616