Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 707
orlp Avatar asked Apr 07 '11 19:04

orlp


People also ask

Is a temporary file in the computer memory?

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 creates temporary files?

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.

What is an example of a temporary file?

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.

What is temporary file system?

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.


2 Answers

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.

like image 110
Robbie Morrison Avatar answered Sep 28 '22 21:09

Robbie Morrison


If you use Qt: QTemporaryFile class is perfect.

like image 28
Naszta Avatar answered Sep 28 '22 22:09

Naszta