views:

2017

answers:

7

In C++, on Linux, how can I write a function to return a temporary filename that I can then open for writing?

The filename should be as unique as possible, so that another process using the same function won't get the same name.

A: 

You should simply check if the file you're trying to write to already exists. This is a locking problem. Files also have owners so if you're doing it right the wrong process will not be able to write to it.

Corporal Touchy
+13  A: 

Use one of the standard library "mktemp" functions: mktemp/mkstemp/mkstemps/mkdtemp.

Edit: plain mktemp can be insecure - mkstemp is preferred.

Andrew Medico
A: 

man tmpfile

The tmpfile() function opens a unique temporary file in binary read/write (w+b) mode. The file will be automatically deleted when it is closed or the program terminates.ote

matli
+5  A: 

tmpnam(), or anything that gives you a name is going to be vulnerable to race conditions. Use something designed for this purpose that returns a handle, such as tmpfile():

   #include <stdio.h>

   FILE *tmpfile(void);
twk
A: 

mktemp should work or else get one of the plenty of available libraries to generate a UUID.

EBGreen
A: 

The tmpnam() function in the C standard library is designed to solve just this problem. There's also tmpfile(), which returns an open file handle (and automatically deletes it when you close it).

Mark Bessey
Don't use tmpnam(). From the man page: "Never use this function. Use mkstemp(3) or tmpfile(3) instead."
twk
Oops. I wasn't paying attention to the "on Linux" part of the question. mkstemp() is probably the right solution, if you don't need portability.
Mark Bessey
A: 

The GNU libc manual discusses the various options available and their caveats:

http://www.gnu.org/s/libc/manual/html_node/Temporary-Files.html

Long story short, only mkstemp() or tmpfile() should be used, as others have mentioned.

Trevor Robinson