FATFileSystem sync


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)
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.

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()
	FATFileSystem sd_card_fs("sd");
	static char buffer[14] = {"Hello World!\n"};
	File testfile;


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

    // 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)));


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: