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

I am moving on to a program that uses temporary files from POSIX FILE to the C ++ standard iostreams library. What is the right alternative to mkstemp?

+8
c ++ libstdc ++ mkstemp
source share
3 answers

There is no portable C ++ way to do this. You need to create a file (which runs automatically when you open the file for writing using ofstream ), and then remove again when you are done with the file (using the C remove library function). 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() 
+3
source share

Not. Note that mkstemp not part of C (C99, at least) or the C ++ standard - it is a POSIX add-on. C ++ only has tmpfile and tmpnam in the library part of C.

Boost.IOStreams , however, provides a file_descriptor device class that can be used to create a thread that works on what mkstemp returns.

If I remember 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; 
+5
source share

If you want a portable solution in C ++, 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 a percent sign to indicate a replacement for a random hexadecimal digit. [Note: the more bits of randomness in the generated path name, the less likely the previous existence or guessed. Each replacement of the hexadecimal digit in the model adds four bits of randomness. Thus, the default model provides 64 bits randomness. This is sufficient for most applications.

+3
source share

All Articles