17

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.

cnicutar
  • 178,505
  • 25
  • 365
  • 392
jorgander
  • 540
  • 1
  • 4
  • 12

1 Answers1

20

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.

cnicutar
  • 178,505
  • 25
  • 365
  • 392
  • 1
    You are correct, and I need to be more thorough when I read the documentation. Call me OCD, but I used the info at [this post](http://stackoverflow.com/questions/4790471/how-can-i-get-the-temporary-directory-path-in-ubuntu) to get the temporary folder instead of simply hard-coding "/tmp"; – jorgander Aug 17 '12 at 15:59
  • If you are creating a file in /tmp/ and then you are planning to move the file to specific location say "/home// then it will take long time to cp or move and it will be even worst if /tmp and /home/ were in different partition area; so better create file in /home//fileXXXXX and rename it to /home//file. – Viswesn Aug 17 '12 at 17:56
  • What is the final filename? – Don Scott Sep 20 '15 at 17:13
  • 1
    @DonScott See the answer again: "and the name of the associated file in `name`". – cnicutar Sep 21 '15 at 00:06