Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there any reasons to avoid using tmpnam() to get a name for a temporary file?

Tags:

c++

c

file-io

I was going to use tmpnam() to name a temporary file that will be renamed later, not deleted. But I found the following documentation and I'm now intrigued about the part that says

"...naive programmers may think it a suitable name for a temporary file."

From http://man7.org/linux/man-pages/man3/tmpnam.3.html

The tmpnam() function returns a pointer to a string that is a valid filename, and such that a file with this name did not exist at some point in time, so that naive programmers may think it a suitable name for a temporary file. If the argument s is NULL this name is generated in an internal static buffer and may be overwritten by the next call to tmpnam(). If s is not NULL, the name is copied to the character array (of length at least L_tmpnam) pointed to by s and the value s is returned in case of success.

Can someone explain why does the documentation say that?

I assume "it" refers to the name generated, and that only naive programmers would think it is adequate to name a temp file, otherwise why mention it? If it isn't an appropriate solution, why does it exist?

I would greatly appreciate if someone could clear it up.

like image 918
2013Asker Avatar asked Oct 21 '22 16:10

2013Asker


1 Answers

Another program may create a file with exactly that name in the meantime. To be sure you can actually get a file with that filename the creation of filename and file itself should be an atomic, indivisible operation.

It's a bit theoretical as the time between the tmpnam() and actual creation is likely to be very short. But still it's possible.

like image 123
erik Avatar answered Oct 24 '22 10:10

erik