I am writing a C++ problem. It need to work on both Windows and Unix OS.
How to get user or system tmp folder on different OS?
Update: Thanks @RoiDanton, the most up to date answer is std::filesystem::temp_directory_path
(C++17)
Try boost::filesystem
's temp_directory_path()
which internally uses:
ISO/IEC 9945 (POSIX): The path supplied by the first environment variable found in the list TMPDIR
, TMP
, TEMP
, TEMPDIR
. If none of these are found, "/tmp"
, or, if macro __ANDROID__
is defined, "/data/local/tmp"
Windows: The path reported by the Windows GetTempPath
API function.
Interestingly, Window's GetTempPath
uses similar logic to the POSIX version: the first environment variable in the list TMP
, TEMP
, USERPROFILE
. If none of these are found, it returns the Windows directory.
The fact that these methods primarily rely on environment variables seems a bit yuck. But thats how it seems to be determined. Seeing as how mundane it really is, you could easily roll your own using cstdlib
's getenv
function, especially if you want specific order prioritization/requirements or dont want to use another library.
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