How to get a temporary file name?
Asked Answered
K

1

19

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.

Killifish answered 17/8, 2012 at 15:0 Comment(0)
C
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.

Cordell answered 17/8, 2012 at 15:7 Comment(4)
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 to get the temporary folder instead of simply hard-coding "/tmp";Killifish
If you are creating a file in /tmp/ and then you are planning to move the file to specific location say "/home/<user>/ 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/<user>/fileXXXXX and rename it to /home/<user>/file.Subjunctive
What is the final filename?Golly
@DonScott See the answer again: "and the name of the associated file in name".Cordell

© 2022 - 2024 — McMap. All rights reserved.