dart-lang / io

Utilities for the Dart VM's dart:io.
https://pub.dev/packages/io
BSD 3-Clause "New" or "Revised" License
49 stars 15 forks source link

File.writeAsString may write corrupted data when flush=true #118

Open giregk opened 9 months ago

giregk commented 9 months ago

On all platforms, the following code

final f = File(...);
unawaited(f.writeAsString('aaa', flush: true));
unawaited(f.writeAsString('b', flush: true));

writes 'baa' to the file.

This ended up creating a crash in my app because the file was no longer a valid json. (My real code was a lot more complex, but it resulted in this kind of result too).

The expected result is to write either 'aaa' or 'b' but not a mix of them.

NOTE 1: This code writes 'aaa' to the file.

final f = File(...);
unawaited(f.writeAsString('aaa', flush: false));
unawaited(f.writeAsString('b', flush: false));

NOTE 2: In my case, the expected result is actually to write the latest content ('b') because I keep a cache of the json in RAM and simply want the latest value to be persisted. To make it behave that way, I used a lock (using the synchronize package) to make sure the latest write request was the used one.