Configuring a File Buffer - POSIX
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.
static CPU_INT32U App_FileBuf[512 / 4]; /* Define file buffer. */ void App_Fnct (void) { CPU_INT08U data1[50]; . . . p_file = FS_fopen("\\file.txt", "w"); if (p_file != (FS_FILE *)0) { (1) /* Set buffer. */ fs_setvbuf(p_file, (void *)App_FileBuf, FS__IOFBF, sizeof(App_FileBuf)); . . . (2) fs_fflush(p_file); /* Make sure data is written to file. */ . . . fs_fclose(p_file); /* When finished, close file. */ } . . . }
(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.
(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.