>From a filesystem point of view, would it be more efficient to invoke ftruncate at the end of writing, rather than at the beginning? That way, if the file already exists and is of the right size, it won't need to be reallocated. We're not trying to write any holes, so this optimization should be valid.
Please don't let this comment slow you down, as your patch is fine as-is. I'm mainly asking because I was wondering about the issue in general.
