C++: Getting a temporary file, cross-platform

I'm looking for a cross-platform way of getting designated a temporary file. For example in linux that would be in the /tmp dir and in Windows in something akin to C:\Users\Username\AppData\Local\Temp.

Does a cross-platform (Boost?) solution to this exist?

EDIT:

I need this file to exist until the program terminates. tmpfile() does not guarantee that. Quoting from ccpreference:

The temporary file created is automatically deleted when the stream is closed (fclose) or when the program terminates normally.


Solution 1:

The Boost Filesystem library, from version 3 of that library, can be used to create a temporary file name. It also offers a crisp solution. Indeed, the following C++ code should be platform independent:

// Boost.Filesystem VERSION 3 required
#include <string>
#include <boost/filesystem.hpp>
boost::filesystem::path temp = boost::filesystem::unique_path();
const std::string tempstr    = temp.native();  // optional

The filesystem path object temp can be used to open a file or create a subdirectory, while the string object tempstr offers the same information as a string.

Solution 2:

If you use Qt: QTemporaryFile class is perfect.

Solution 3:

The standard C library contains a function called tmpfile, it probably does what you need: http://www.cplusplus.com/reference/clibrary/cstdio/tmpfile/

You can use it in C++ programs as well.

EDIT:
If you need only file name, you can use tmpnam, it doesn't delete the file when fclose is called. It returns full file path, including the temp directory.

The C way:

const char *name = tmpnam(NULL);  // Get temp name
FILE *fp = fopen(name, "w");  // Create the file
// ...
fclose(fp);
remove(name);

Solution 4:

You can use the C Standard Library function tmpfile.