Follow a FAT cluster chain
List a file's clusters from the allocation table, and refuse a chain that is corrupt. A medium embedded C problem (Embedded file systems), run and graded in…
medium · Embedded file systems · fat · file-system · linked-list · robustness
In a FAT file system a file's data is a linked list of clusters. The directory entry gives the first cluster, and fat[c] gives the cluster after c, or FAT_EOC for the last one. Data clusters are numbered from 2 to nclusters - 1.
Write fat_chain(fat, nclusters, start, out): write the file's clusters in order into out (which has room for nclusters entries) and return how many there are. A start of 0 means an empty file: return 0.
Cards get corrupted, and firmware must not hang or read wild memory when they do. Return -1 if the chain starts or continues at a cluster outside 2 to nclusters - 1, reaches a free or bad cluster, or loops back on itself.
Starter code
int fat_chain(const uint16_t *fat, uint16_t nclusters, uint16_t start, uint16_t *out) {
int n = 0;
uint16_t c = start;
while (c != FAT_EOC) {
out[n++] = c;
c = fat[c];
}
return n;
}Example tests
A file in four clusters
uint16_t fat[16] = {0};
fat[2] = 3; fat[3] = 7; fat[7] = 4; fat[4] = FAT_EOC;
fat[5] = FAT_EOC;
show(fat, 16, 2);
show(fat, 16, 5);Expected output:
4: 2 3 7 4
1: 5A chain that runs into a free cluster
uint16_t fat[16] = {0};
fat[8] = 9;
show(fat, 16, 8);Expected output:
corruptLearn it first
- Embedded file systems · FatFs, LittleFS and designing a reliable data logger.
More Embedded file systems problems
- Fix: the log loses its last line · A data logger syncs on every line, yet the newest line is always missing after a power cut.