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.
Temporary files, also referred to as TMP files, are automatically created and deleted from a computer. They store data temporarily which means they need less memory and thus improve the performance of a computer.
What are temporary files? Temporary files, also called temp or tmp files, are created by Windows or programs on your computer to hold data while a permanent file is being written or updated. The data will be transferred to a permanent file when the task is complete, or when the program is closed.
Techopedia Explains Temporary File In terms of backup purposes, Microsoft's Office applications are good examples of this. For example, Microsoft Word and Excel save a temporary file associated with the current open document that it points to after a computer has recovered from a crash or power outage.
The temporary file system (TFS) is an in-memory physical file system that supports in-storage mountable file systems and is not written to DASD. Putting the temporary data in a separate file system makes it easier to manage the space used by temporary files.
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.
If you use Qt: QTemporaryFile class is perfect.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With