write_file(), as written wasn't transaction-safe; a crash bewtween a
file being open and the buffer being written before a safe close would
leave the file with a set of undetermined contents.
Modified to the file is written to a temporary file name; once
completed, it is renamed to the final name. This way, a crash in the
middle doesn't leave half-baked files.
- Remove reference to g_malloc and replace with g_try_malloc
- Be extra pedantic on the inputs
- Refactor the logic to make it slightly easier to follow