Reputation: 83
I am writing data to a file, however on sudden power offs I can see garbage data in the file sometimes.
Sometimes the data is missing, sometimes it is editted and sometimes its a garbage data just before my first entry to the file on system reboot.
Is there a way I can make sure fwrite is consistent?
Just to add I am using "a" to append data to the file everytime.
Further, the garbage values or indermined data which I am seeing in the file, is it really due to the fwrite() operation?
Upvotes: 2
Views: 1907
Reputation: 30250
It depends what implementation of FAT your embedded OS is using. If you're using smxFS, then you should take advantage of the following:
The DOS/Windows FAT file system is inherently not power fail safe, so smxFS
implements features to compensate for this:
1. sfs_chkdsk() API can check and fix many problems, such as cross-linked
files, lost chains, bad directory entries, and other problems. Flags specify
which types of problems to fix (or none). It indicates the results using flags
in the return value and can give detailed text information in a buffer, to
allow a human operator to correct problems. Please see the smxFS User’s Guide
for details.
2. Clean shutdown checking determines whether all files were closed and
caches flushed before the system shut down. If not, sfs_chkdsk() should be called.
If you expect unexpected power losses, you should consider a capacitor or backup battery that will allow you to finish a write correctly. You'd probably want sfs_fflush and sfs_fclose (or maybe even sfs_fclose, as it looks like it flushes itself)
There are other filesystem options listed here, although they might not all be suitable for your application as not all of them can be read OOB by a computer.
Upvotes: 0
Reputation: 43558
Right after writing, call fflush(3)
(to flush user-space buffers), and then either fsync(2)
or fdatasync(2)
to make sure that all the data has been written to the device.
Upvotes: 3
Reputation: 70721
FAT32 is not a journaling filesystem, so there is no way to guarantee consistent writes. Even if you flush the disk buffers after each write, the data could still be corrupted if there is a power loss just as the data is written to disk.
To answer your other question, no, the garbage isn't caused by fwrite
at all, it is because the filesystem has not completed the write operation in its entirety.
Upvotes: 3