You're leaking the file descriptor this returns; and calling fopen() on tmp below is all wrong.  (The point of mkstemp is to avoid a race condition that becomes possible again if you fopen() the same name a moment later; someone could have moved aside the file mkstemp() created and replaced it by a symlink, which is exactly what you were supposed to avoid by calling mkstemp instead of tempnam.)  You should collect mkstemp()'s returned file descriptor and call fdopen() on it in place of fopen (or re-write the code below to use a file descriptor instead of a stream).