Question

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.

Was it helpful?

Solution

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

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

OTHER TIPS

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);

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.

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

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

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).

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top