11 years, 4 months ago.

Forcing a write to a file on a SD...

I need to be able to write to an SD card and force the write on each line (logging GPS NMEA data) without having to close and reopen the file.

I've tried using fflush() after my write:

fputs(buffer, gps_file);
fflush(gps_file);

When I remove power to test if it was working the file is empty.

I've also tried changing the buffering to line buffering:

FILE *gps_file = fopen("/sd/hab/gps.log", "w");
char line_buff[1024];
setvbuf ( gps_file , line_buff, _IOLBF, 1024);

And I've tried preventing any buffering:

FILE *gps_file = fopen("/sd/hab/gps.log", "w");
setvbuf ( gps_file , NULL, _IONBF, 0);

Both of these give the blue lights of death and never make it past the setbvuf line. What am I doing wrong?

Edit: I found a comment on the forums that suggested using disk_sync(). However when I searched through SDFileSystem and FATFileSystem I found that it was there but not implemented (it simply returns 0).

Please help.

1 Answer

6 years, 12 months ago.

Have you found solution of this problem?

Sarah, As the origional question indicated, all that function in File.cpp does is call the file system sync function which is defined here: https://github.com/ARMmbed/mbed-os/blob/master/features/filesystem/FileSystem.cpp#L28-L31

The solution I've ended up with for this is to periodically close and re-open the file, either using a Ticker to do this or after writing a certain number of bytes depending on the situation.

Far from perfect but it avoids the overhead of closing and opening every single write while setting an upper limit on the amount of data lost if the card is unexpectedly removed or power cut. Just remember to re-open in append mode not write mode.

posted by Andy A 24 Apr 2017