Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

In order to increase the efficiency of file reads and writes, input/output buffering capabilities are provided. Without an assigned buffer, reads and writes will be immediately performed within fs_fread() and fs_fwrite(). Once a buffer has been assigned, data will always be read from or written to the buffer; device access will only occur once the file position moves beyond the window represented by the buffer.

fs_setbuf() and fs_setvbuf() assign the buffer to a file. The contents of the buffer can be flushed to the storage device with fs_fflush(). If a buffer is assigned to a file that was opened in update (read/write) mode, then a write may only be followed by a read if the buffer has been flushed (by calling fs_fflush() or a file positioning function). A read may be followed by a write only if the buffer has been flushed, except when the read encountered the end-of-file, in which case a write may happen immediately. The buffer is automatically flushed when the file is closed.

File buffering is particularly important when data is written in small chunks to a medium with slow write time or limited endurance. An example is NOR flash, or even NAND flash, where write times are much slower than read times, and the lifetime of device is constrained by limits on the number of times each block can be erased and programmed.

Listing 10-3 Example file buffer usage

L10-3(1) The buffer must be assigned immediately after opening the file. An attempt to set the buffer after read or writing the file will fail.

L10-3(2) While it is not necessary to flush the buffer before closing the file, some applications may want to make sure at certain points that all previously written data is stored on the device before writing more.