# FatFs strange behavior when writing to text file

I wrote a small program with PIC32MX microcontroller that sends data to a txt file in the SD card, then reads the data back from the file and finally compares the data before sending them with the data after sending them, from the txt file of the SD.

I do this, to check if the bytes are saved/retrieved correctly (or not) to/from the txt file created in the SD card.

Data consist of only two characters, 'G' and 'H' . First I write 500 Bytes of 'G's and then 500 Bytes of 'H's. repeatedly for 10 times and the total number of bytes in the txt file would be 10kB.

Also, data in the txt file of the SD would appear like this: GGG...HHH...GGG...HHH... etc. To write these data to the file I use the f_write() function

FRESULT f_write (
FIL* fp,          /* [IN] Pointer to the file object structure */
const void* buff, /* [IN] Pointer to the data to be written */
UINT btw,         /* [IN] Number of bytes to write */
UINT* bw          /* [OUT] Pointer to the variable to return number of bytes written */
);


And here lies the problem. When I set the Number of bytes to write, to 1000 bytes(500 'G's and 500 'H's, the result in the txt file is only GGGGG... with no'H's. When I double the number of bytes to write, from 1000 to 2000, only then GGG...HHHH...GGG...HHH sequence appears correctly.

And the question is, why is this happening. Normally the latter (correct) result should occur when I set the exact number of bytes to write, in the function (1000) and not by doubling it(2000)

Any idea why this happens?

• something is wrong with your program. perhaps buf is not filled correctly. – Jasen May 4 '18 at 10:33
• It may to do with the size of the data versus the size of the blocks in the SD card. Writes smaller than a full SD block may be getting buffered. Have you tried flushing the writes before doing the reads, or even just writing in chunks the same size as the SD blocks? – crj11 May 4 '18 at 10:56
• Thank you Guys. What do you mean by flushing the writes? I have two buffers one for sending data to the SD file and one buffer for reading data from that txt – Sparky May 4 '18 at 11:01
• As crj11 says: To debug it is better to start with complete SD card sectors, most of which are set to 512 bytes. – Oldfart May 4 '18 at 11:47
• ok I will check it out and I'll tell you what happened – Sparky May 4 '18 at 12:14