1

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

anishtain4
  • 2,342
  • 2
  • 17
  • 21
  • 1
    From [f_printf](http://elm-chan.org/fsw/ff/doc/printf.html): `When the string was written successfuly, it returns number of character encoding units written to the file. When the function failed due to disk full or any error, an EOF (-1) will be returned.` – KamilCuk Feb 19 '20 at 18:42

1 Answers1

2

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.

w08r
  • 1,639
  • 13
  • 14
  • You are absolutely correct. It's clearly mentioned in the docs, don't know why I was checking for `FRESULT`. – anishtain4 Feb 19 '20 at 19:24