2020-05-28 08:08 AM
Hello everybody,
using Fatfs and f_write, when writing the file "1, 2, 3, 4" to the SDCard, I can see that what is written on the SDCard is "0,0,0,0,1,2,3,4" . What layer is inserting the 4 "0" at the beginning of the file and why ? Is it an 32bits alignment problem , Obviously, the f_read reads this 4 "0" header and leads to an error when verifying the data.
Thanks for your help.
o.
2020-05-28 09:41 AM
Might be more obvious why if you show the code.
Perhaps alignment, but could be how you f_open() the file, and if it tries to append.
2020-05-28 12:27 PM
Thanks Clive,
Here is the code, nothing new, following some classical examples. I hope it helps. I was hoping to find the exact string in the file but editing the content shows nul nul nul nul This is Test programming
char bufferwr[30] = "This is Test programming\n\r";
char bufferrd[30];
.
.
.
.
res = BSP_SD_Init();
if(res != FR_OK)
{
Error_Handler();
}
res = f_mount(&SDFatFS, "", 1);
if(res != FR_OK)
{
Error_Handler();
}
res = f_open(&myFile, "test1.txt", FA_OPEN_ALWAYS| FA_WRITE | FA_READ);
if(res != FR_OK)
{
Error_Handler();
}
res = f_lseek(&myFile, sizeof(&myFile));
if(res != FR_OK)
{
Error_Handler();
}
res = f_write(&myFile, bufferwr, 30, (UINT*)&byteswritten);
if((byteswritten == 0) || (res != FR_OK))
{
Error_Handler();
}
res = f_close(&myFile);
if(res != FR_OK)
{
Error_Handler();
}
res = f_open(&myFile, "test1.txt", FA_READ);
if(res != FR_OK)
{
Error_Handler();
}
res = f_read(&myFile, bufferrd, 30, (UINT*)&bytesread);
if((bytesread == 0) || (res != FR_OK)) /* EOF or Error */
{
Error_Handler();
}
res = f_close(&myFile);
if(res != FR_OK)
{
Error_Handler();
}
res = f_mount(0, "", 1);
if(res != FR_OK)
{
Error_Handler();
}
2020-05-28 12:31 PM
> res = f_lseek(&myFile, sizeof(&myFile));
This moves the write pointer to byte 4 and is unlikely to be what you intended. Since you just want to write at the beginning of the file, use offset of 0 (or probably just omit this line).
2020-05-28 01:26 PM
If you REALLY want to seek to the end of the file, surely
res = f_lseek(&myFile, f_size(&myFile));
2020-05-28 01:34 PM
Thanks you guys for your answers. To be honest, I was wondering why using the f_lseek in the example i copied.... Your answers make sense to me now. Thanks again Clive and TDK.