Versions Compared

Key

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

...

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

...

Code Block
languagecpp
titleListing - Example file buffer usage
linenumberstrue
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.           */
    }
    .
    .
    .
}


Panel

(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.