Search code examples
stm32fatfs

Data overwritten when opening file using FatFs


If I close a file and then reopen it, I cannot write more data to it after reopening it, but if i keep it open i can write as many lines as i want then close it when i am finish writing. See the example below. Thanks.

if (f_mount(&FatFs, "", 1) == FR_OK) {
      f_mkdir ("TEST");

      count = 0;
      while(count < 200){

          if(f_open(&fil, "TEST/test.txt", FA_OPEN_ALWAYS | FA_WRITE) != FR_OK){
              break;
          }
          else{
              sprintf(array,"This is file entry number: %d\r\n",count);
              f_puts(array, &fil);
              if(f_close(&fil) != FR_OK){
                  break;
              }
          }
          count++;
      }
      f_mount(0, "", 1);
}

It will count to the max value but it will only write the last entry which is 199.


Solution

  • You need to set your open mode so that it appends to the file rather than writing at the start:

    From f_open

    FA_OPEN_APPEND Same as FA_OPEN_ALWAYS except read/write pointer is set end of the file.

    When you open the file with this:

    f_open(&fil, "TEST/test.txt", FA_OPEN_ALWAYS | FA_WRITE);
    

    you are opening the file for writing with the write pointer at the start of the file, so when you go to write to the file with:

    f_puts(array, &fil);
    

    you overwrite the previous data in the file.

    If you change your open to:

    f_open(&fil, "TEST/test.txt", FA_OPEN_APPEND | FA_WRITE);
    

    then you should get the behavior you desire. There is an exception, though, and that's that each time running this, you will continue appending to the file. If that isn't desired, you may need to delete the file first or open it initially with FA_OPEN_ALWAYS and then re-open each pass with FA_OPEN_APPEND.


    Depending on what you are trying to do, you should take a look at f_sync, which will perform all clean up and writes that an f_close would perform, but keeps the file open. From the documentation:

    This is suitable for the applications that open files for a long time in write mode, such as data logger. Performing f_sync function of periodic or immediataly after f_write function can minimize the risk of data loss due to a sudden blackout or an unintentional media removal.

    This would cover nearly every case I can think of for why you might be repeatedly opening and closing a file to append data, so this may be a better solution to your problem.