Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get system or user temp folder in unix and windows?

Tags:

c++

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?

like image 665
performanceuser Avatar asked Nov 10 '11 23:11

performanceuser


1 Answers

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.

like image 130
Preet Kukreti Avatar answered Sep 29 '22 03:09

Preet Kukreti