Try harder not to store a corrupted build graph.

- Check status of output stream at the end of the serialization process.
- Check whether the data can actually be written to the disk.
- Write the magic string only at the very end, so that if storing gets
interrupted halfway through (e.g. due to a crash), we won't try to load
this file on the next invocation.

Change-Id: I43fed5e9a3516d4d6d66960b4af597019d1d0297
Reviewed-by: Joerg Bornemann <joerg.bornemann@digia.com>