Close handle on new temporary files before returning filename

On Windows, a file can only have one open writable handle at a time, so we need to close the one created by mkstemp before anything else can use that file.

Closes gh-5946