How to get a temporary file name?

14.6k views Asked by At

I've seen some posts relating to my question, but none that address it completely. I need to create a file in the standard temporary directory and after I'm done writing to it, move it to a different location. The idea is that the file is considered temporary while being downloaded and permanent after downloading completes.

I'm attempting this by calling either mkstemp or tmpfile, then rename after I'm done writing to it. However, I need the full path of the file to call rename, and apparently getting the file name from a file descriptor (returned by mkstemp) or FILE * (returned by tmpfile) is no trivial process. It can be done, but it's not elegant.

Is there a system call that will create a temporary file and provide me with the name? I know about mktemp and related calls, but they either aren't guaranteed to be unique or are deprecated. Or perhaps there is a better way to accomplish creating, writing to, and moving temporary files.

1

There are 1 answers

4
cnicutar On BEST ANSWER

It looks like mkstemp is actually the way to go.

int fd;
char name[] = "/tmp/fileXXXXXX";
fd = mkstemp(name);
/* Check fd. */

After this call you have a valid descriptor in fd and the name of the associated file in name.