Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the C++ standard library equivalent for mkstemp?

I am transitioning a program that uses temporary files from POSIX FILE to C++ standard library iostreams. What's the correct alternative to mkstemp?

like image 364
vy32 Avatar asked Oct 15 '11 15:10

vy32


3 Answers

There is no portable C++ way to do it. You need to create a file (which is done automatically when opening a file for writing using an ofstream) and then remove it again when you're finished with the file (using the C library function remove). But you can use tmpnam to generate a name for the file:

#include <fstream>
#include <cstdio>

char filename[L_tmpnam];
std::tmpnam(filename);
std::fstream file(filename);
...
std::remove(filename);   //after closing, of course, either by destruction of file or by calling file.close()
like image 151
Christian Rau Avatar answered Nov 12 '22 09:11

Christian Rau


If you want a portable C++ solution, you should use unique_path in boost::filesystem :

The unique_path function generates a path name suitable for creating temporary files, including directories. The name is based on a model that uses the percent sign character to specify replacement by a random hexadecimal digit. [Note: The more bits of randomness in the generated path name, the less likelihood of prior existence or being guessed. Each replacement hexadecimal digit in the model adds four bits of randomness. The default model thus provides 64 bits of randomness. This is sufficient for most applications

like image 32
anno Avatar answered Nov 12 '22 09:11

anno


There is none. Note that mkstemp is not part of either C (C99, at least) or C++ standard — it's a POSIX addition. C++ has only tmpfile and tmpnam in the C library part.

Boost.IOStreams, however, provides a file_descriptor device class, which can be used to create a stream operating on what mkstemp returns.

If I recall correctly, it should look like this:

namespace io = boost::iostreams;

int fd = mkstemp("foo");
if (fd == -1) throw something;

io::file_descriptor device(fd);
io::stream<io::file_descriptor> stream(device);

stream << 42;
like image 6
Cat Plus Plus Avatar answered Nov 12 '22 08:11

Cat Plus Plus