Fix potential file corruption with partial writes