SdFat Corrupt Files

I am using the SdFat library to write files to my sd card and have encountered an issue where if power is disconnected mid write, the file becomes corrupted. I can easily trigger this b/c it is a file that is often written to. What I mean by corrupt is that the file appears to function normally, except that it cannot be deleted thru firmware, requiring me to delete it with my computer, which is not feasible for production. On my computer, the file content cannot be viewed and has a size of 0, whereas according to SdFat, it is the correct size (~80 bytes), even after corruption.

Is there a way to deal with or detect SdFat file corruption? I have seen some issues in brought up in the SdFat github page, but no solutions.

I have found that by calling truncate on a corrupted file, I can delete it afterwards in firmware, but I am doubtful on its safety as it causes all sorts of strange behavior when I view the sd card on my computer afterwards. For instance, getting clones of the corrupted file with the same file name and size.

1 Like

Unfortunately this seems to be an issue with the SdFat library, I’ve searched and there does not seem to be a known solution. Have you brought this up with the library creator?

I have and it looks like all I can really do is minimize the chance of corruption with frequent calls of sync.

My plan is to make use of guard files, which I can create before any major sd card write and then delete afterwards, that way in the event of power failure, if this guard file exists then I will know that corruption likely occurred. Could also use EEPROM for a similar check mechanism.

1 Like

That’s too bad, but your plan sounds solid.

I have found that files seem to work on the sd card, but they too can get corrupted, unfortunately. This atleast prevents my main file from getting corrutped though.
EEPROM seems pretty slow, unfortunately, taking about 200 ms to write a byte ( I only tried writing a single byte at a time, but I am guessing it is probably faster at writing multiple bytes at once).

I am also considering using the onboard POSIX file system, since its built off of littleFS, which claims to be resilient against power failure. This should work for smaller files, but I am wondering if there is a library that interacts with an sd card like littleFS does with flash memory?

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.