Close open file handles; use mkstemp and write with 'wb'