cancel
Showing results for 
Search instead for 
Did you mean: 

FatFS append file only once opened

Posted on December 10, 2015 at 15:28

Hello there,

I have a logger application on a STM32F407 device. I am saving logs to sd card. Generally it works, but I would like to make the procedure a bit faster by opening the file only once at the begining of the program. The problem is when I do that, I dont get anything saved... This is my ''append to file'' procedure:

static HAL_StatusTypeDef log_AppendFileSdCard(uint8_t* text, uint32_t length)
{
FRESULT res;
uint32_t bytesWritten = 0;
if (FR_OK != f_open(&log_File, (const TCHAR*)logName, FA_WRITE))
return HAL_ERROR;
if (FR_OK != f_lseek(&log_File, f_size(&log_File)))
{
return HAL_ERROR;
}
res = f_write(&log_File, text, length, (void *)&bytesWritten);
if((bytesWritten > 0) && (res == FR_OK))
{
if (FR_OK != f_close(&log_File))
{
return HAL_ERROR;
}
}
else
{
return HAL_ERROR;
}
return HAL_OK;
}

If for example, I create the file and leave it opened, and remove the open/ close functions from my procedure:

static HAL_StatusTypeDef log_AppendFileSdCard(uint8_t* text, uint32_t length)
{
FRESULT res;
uint32_t bytesWritten = 0;
if (FR_OK != f_lseek(&log_File, f_size(&log_File)))
{
return HAL_ERROR;
}
res = f_write(&log_File, text, length, (void *)&bytesWritten);
if((bytesWritten > 0) && (res == FR_OK))
{
// dont close
}
else
{
return HAL_ERROR;
}
return HAL_OK;
}

There is nothing saved to the file, even though write doesnt return any error and the index of the file struct is incremented. What could be the case here, am I doing something wrong? I would apreciate all help!
4 REPLIES 4
AvaTar
Lead
Posted on December 10, 2015 at 15:43

Have you tried to call

f_sync()

after

f_write()

?

thomfischer
Senior
Posted on December 10, 2015 at 15:48

I open my logfile with flags ''

FA_OPEN_ALWAYS | FA_WRITE | FA_READ

''

f_lseek is only needed once after f_open,

maybe, if you use it in your log function, f_size(&log_File) does not get updated after every write ?

Posted on December 10, 2015 at 15:54

This was the case, thank you!

Posted on December 10, 2015 at 16:55

This is a working function:

static HAL_StatusTypeDef log_AppendFileSdCard(uint8_t* text, uint32_t length)
{
assert_param(text);
FRESULT res;
uint32_t bytesWritten = 0;
if (FR_OK != f_lseek(&log_File, f_size(&log_File)))
return HAL_ERROR;
res = f_write(&log_File, text, length, (void *)&bytesWritten);
if((bytesWritten > 0) && (res == FR_OK))
{
res = f_sync(&log_File);
if (FR_OK != res)
return HAL_ERROR;
}
else return HAL_ERROR;
return HAL_OK;
}