Search code examples
cembeddedfatfs

How to get largest free contiguous block of memory in FatFs


Using the FatFs and their API, I am trying to pre-allocate file system space for the remainder of the drive to write files of unknown sizes. At the end of the file write process, any unused space is then truncated (f_truncate). However, I'm having a problem allocating enough space when the file system become fragmented after deletion of some files. To overcome this problem, I would like to allocate only enough space as the largest contiguous block of memory on the file system.

In the FatFS API, there are functions to get the amount of free space left on the device, which is f_getfree. There is also the f_expand function, which takes in a size in bytes and returns whether or not a free contiguous block of memory exists for that given size.

Is there an efficient way to calculate the largest free contiguous block of memory available? I'm trying to avoid any sort of brute force "guess and check" method. Thanks


Solution

  • One way would be to create your own extension to the API to count contiguous FAT entries across all the sectors.

    Without modifying the API, you could use f_lseek(). Write open a file, use f_lseek() to expand the size of the file until 'disk full'(end of contiguous space). This would need to be repeated with new files until all of the disk was allocated. Pick from this the maximum allocated file, and delete the others.