Page 1 of 1

Reading the FAT

Posted: Tue Mar 13, 2007 1:39 am
by pcmattman
Does anyone have any C code for reading the FAT? At the moment, I've read in the FAT but am stuck trying to figure out how to work with it. The main problem is that it's on a FAT12 and that means that each cluster entry is 12 bits. The code I've tried is a bit like this:

Code: Select all

printf( "Cluster %d: %d", f, FATable[f] >> 4 );
FATable is a buffer containing all the sectors of the FAT. Unfortunately, the results from this are confusing, to say the least. The first four entries are all -1, others are 0, some are numbers. I'm really confused :(.

Posted: Tue Mar 13, 2007 3:40 am
by Combuster
what goes wrong here is that the entries are packed:

Code: Select all

| byte 1 | byte 2  | byte 3 |
+--------+----+----+--------+
|10101010|1010|1010|10101010|  sector contents
+--------+----+----+--------+
| FAT entry 1 | FAT Entry 2 |
so you would end up with something like this to get a fat entry:

Code: Select all

char * FAT;

int getFatEntry(int i) 
{
    int offsetbyte = (i >> 1) * 3
    int sign = i & 1;
    int data;

    // NOTE: i have not tested the decoding here. It might not work.
    if (sign) == 0
    {
        data = FAT[offsetbyte] + ( (FAT[offsetbyte+1] & 0xf) << 8) & 0xfff;
    } else {
        data = (FAT[offsetbyte+1] + (FAT[offsetbyte+2] << 8) ) >> 4;
    }
    return(data);
}
You should check with the FAT page in the wiki - it tells you everything you need.

Posted: Tue Mar 13, 2007 4:21 am
by pcmattman
Thankyou, I'll look into that.