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

vy32 picture vy32 · Oct 15, 2011 · Viewed 10k times · Source

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

Answer

Cat Plus Plus picture Cat Plus Plus · Oct 15, 2011

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;