c - 如何使 fwrite() 在将数据写入文件时保持一致



我正在将数据写入文件,但是在突然断电时,我有时会在文件中看到垃圾数据。

有时数据丢失,有时被

编辑,有时它是我在系统重新启动时首次进入文件之前是垃圾数据。

有没有办法确保 fwrite 是一致的?

补充一点,我每次都使用"a"将数据附加到文件中。

此外,我在文件中看到的垃圾值或内层数据,真的是由于 fwrite() 操作造成的吗?

FAT32 不是日志文件系统,因此无法保证写入的一致性。即使在每次写入后刷新磁盘缓冲区,如果在将数据写入磁盘时断电,数据仍可能损坏。

回答你的另一个问题,不,垃圾根本不是由fwrite引起的,这是因为文件系统没有完全完成写入操作。

写入后,立即调用 fflush(3)(刷新用户空间缓冲区),然后fsync(2)fdatasync(2)以确保所有数据都已写入设备。

这取决于您的嵌入式操作系统使用的FAT实现。 如果您使用的是 smxFS,则应利用以下内容:

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.

如果您预计会出现意外的功率损耗,则应考虑使用电容器或备用电池,以正确完成写入。 你可能想要sfs_fflush和sfs_fclose(甚至可能是sfs_fclose,因为它看起来像是自己冲洗的)

此处还列出了其他文件系统选项,尽管它们可能并不都适合您的应用程序,因为并非所有文件系统选项都可以由计算机读取 OOB。

最新更新