Simvik

Fix: the log loses its last line

A data logger syncs on every line, yet the newest line is always missing after a power cut. An easy embedded C problem (Embedded file systems), run and…

easy · Embedded file systems · find-the-bug · file-system · power-loss · cache

Bug report. A data logger writes one line per measurement and calls fs_sync for every line, so that a power cut loses nothing. In the field, the log on the card is always missing its newest line after a power cut.

fs_write and fs_sync behave like FatFs's f_write and f_sync and are known to be correct. Find the defect in log_line and fix it, changing at most two lines.

Starter code

void log_line(file_t *f, const char *line) {
  fs_sync(f);
  fs_write(f, line, (int)strlen(line));
}

Example tests

Three measurements, then the power goes

file_t f = {0};
log_line(&f, "t=1 20.5C\n");
log_line(&f, "t=2 20.7C\n");
log_line(&f, "t=3 21.0C\n");
power_cut(&f);

Expected output:

t=1 20.5C
t=2 20.7C
t=3 21.0C
(30 bytes)

Learn it first

More Embedded file systems problems