I have a small piece of code that opens a file, reads a single number, adds one and writes it back to the file.
It works fine when I use f_write
, but f_open
returns FR_INT_ERR
.
I'm using version R0.12c.
The code that generates error:
FIL indexFile;
char chars[10] = {0};
uint16_t indexNumber = 0;
FRESULT fr;
fr = f_open(&indexFile, INDEX_NAME, FA_READ | FA_WRITE | FA_OPEN_EXISTING);
fr = f_read(&indexFile, &chars, 10, &br);
indexNumber = atoi(chars);
fr = f_lseek(&indexFile, 0);
fr = f_printf(&indexFile, "%d", indexNumber+1); // produces assertion error
if (fr != FR_OK) printf("Something went wrong");
But if I change fr = f_printf(&indexFile, "%d", indexNumber+1);
to the following, it does not complain:
char stringBuffer[5];
sprintf(stringBuffer, "%d", indexNumber+1);
UINT bw;
fr = f_write(&indexFile, stringBuffer, strlen(stringBuffer), &bw);
if (fr != FR_OK || strlen(stringBuffer) != bw) printf("something went wrong");
Although I can keep using the second approach but I'm the type of person who needs to understand what is wrong.
BTW: I'm using STM32
I believe that f_write
does indeed return an FRESULT
but that f_printf
will return an int
indicating the number of characters written. Therefore, checking for F_OK
as a return does not make sense. You need to instead assert based on the input format string,
Edit: as per @KamilCuk comment, EOF (-1) will be returned on failure, so test for that.