FATFileSystem sync

Hi,

is there a good method how to use the file_sync() member of FATFileSystem.h? I just put file_sync() as a public member of FATFileSystem in my local copy, for testing purposes.

Then I am calling it on my local defined FATFileSystem giving it an input parameter of type FILE* .

SDBlockDevice sd_card_bd;
FATFileSystem sd_card_fs;

int SD_Card_Wrapper::do_some_sync( FILE* filename)
{
fflush(filename);
sd_card_bd.sync();
int err = sd_card_fs.file_sync(filename);
return err;
}

the return of file_sync is -9 (The file/directory object is invalid, see FATFileSystem.cpp).

Am I giving the wrong input type (File* or FileHandle* instead of FILE*)? Is there some description on how the File classes and casting of FileClasses works?

From the following link I got note that FATFileSystem is responsible for synchronizing the file.
https://os.mbed.com/forum/mbed/topic/32521/

My plan is to log data regularily to a SD Card and syncing should help me to prevent dataloss (instead of closing and reopening the file, which would return EOF on my filepointer inbetween).

Any ideas, or anyone that experienced similar problems?

I solved the problem on my own:

The example proclaimed in e.g. File - API references and tutorials | Mbed OS 6 Documentation is entirely missleading. The example uses only std::FILE pointers (streams) and no mbed::File instances at all.

I was coming up with the following program:

void testloop()
{
	SDBlockDevice sd_card_bd(SD_MOSI_PIN, SD_MISO_PIN, SD_CLK_PIN, SD_CS_PIN, SD_DETECT_PIN);
	FATFileSystem sd_card_fs("sd");
	sd_card_fs.mount(&sd_card_bd);
	static char buffer[14] = {"Hello World!\n"};
	File testfile;

	ThisThread::sleep_for(300ms);

	printf("Open returns: %d,\n", testfile.open(&sd_card_fs, "testfile.csv", O_CREAT));
	testfile.close();

    // Reopening with RW attributes
	printf("Open returns: %d,\n", testfile.open(&sd_card_fs, "testfile.csv", O_RDWR));    	

	printf("Write returns: %d,\n", testfile.write(buffer, sizeof(buffer)));

	printf("Sync returns: %d,\n", testfile.sync());
	
	printf("Write returns: %d,\n", testfile.write(buffer, sizeof(buffer)));

	while(true)
	{}
}

This example shows that sync is working as intended (only one line gets written to the file after powering the system off). This functionality is not implemented in the std::FILE classes and fprintf streams.

Since no printf etc. is being used, the implementation is Thread-Safe, though can’t be used in an Interrupt cotext, since FATFileSystem is built upon Mutexes.

What has to be tested yet is if it is possible to sync() the file asynchronously to see if e.g. a write to the underlying buffer can happen whilst the buffer gets synced to the SD. If I am at this point, I will probably send an update.

1 Like

thanks @tbitenc for the update! I will soon look into this for our product and your findings will be helpful :slight_smile: