Getting user temporary folder path in Windows

46,706

Solution 1

Is there a reason you can't use the Win32 GetTempPath API?

This API is available starting with W2K and hence will be available on all of your listed targets.

Solution 2

Since C++ 17 you can use a cross-platform function: std::filesystem::temp_directory_path()

https://en.cppreference.com/w/cpp/filesystem/temp_directory_path

Solution 3

In Windows 10, this can be tricky because the value of the Temporary Path depends not only what it's set to by default, but also what kind of app you're using. So it depends what specifically you need.

[Common Area] TEMP in User's Local App Data

#include <Windows.h>
#include <Shlobj.h>
#include <Shlobj_core.h>
#include <string_view>
// ...
static void GetUserLocalTempPath(std::wstring& input_parameter) {
    static constexpr std::wstring_view temp_label = L"\\Temp\\";
    HWND folder_handle = { 0 };
    WCHAR temp_path[MAX_PATH];
    auto get_folder = SHGetFolderPath( 
        folder_handle, CSIDL_LOCAL_APPDATA, NULL, SHGFP_TYPE_DEFAULT, temp_path
    );
    if (get_folder == S_OK) {
        input_parameter = static_cast<const wchar_t*>(temp_path);
        input_parameter.append(temp_label);
        CloseHandle(folder_handle);
    }
}

GetUserLocalTempPath will likely return the full name instead of the short name.
Also, if whatever is running it is doing it as as SYSTEM instead of a logged in user, instead of it returning %USERPROFILE%\AppData\Local\Temp, it will return something more like, C:\Windows\System32\config\systemprofile\AppData\Local\Temp

Temp for whatever the TEMP environment variable is

#include <Windows.h>
// ...
static void GetEnvTempPath(std::wstring& input_parameter) {
    wchar_t * env_var_buffer = nullptr;
    std::size_t size = 0;
    if ( _wdupenv_s(&env_var_buffer, &size, L"TEMP") == 0 &&
         env_var_buffer != nullptr) {
        input_parameter = static_cast<const wchar_t*>(env_var_buffer);
    }
}

[Robust] Temp for whatever is accessible by your app (C++17)

#include <filesystem>
// ...
auto temp_path = std::filesystem::temp_directory_path().wstring();

temp_directory_path will likely return the short name instead of the full name.


You're probably going to get the most use out of the first and last functions depending on your needs. If you're dealing with AppContainer apps, go for the last one provided by <filesystem>. It should return something like,

C:\Users\user name\AppData\Local\Packages\{APP's GUID}\AC\Temp

Solution 4

The GetTempPath function retrieves the path of the directory designated for temporary files. This function supersedes the GetTempDrive function.

DWORD GetTempPath(

DWORD nBufferLength, // size, in characters, of the buffer 
LPTSTR lpBuffer // address of buffer for temp. path 
); 

Parameters

nBufferLength

Specifies the size, in characters, of the string buffer identified by lpBuffer.

lpBuffer

Points to a string buffer that receives the null-terminated string specifying the temporary file path.

Return Values

If the function succeeds, the return value is the length, in characters, of the string copied to lpBuffer, not including the terminating null character. If the return value is greater than nBufferLength, the return value is the size of the buffer required to hold the path. If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

The GetTempPath function gets the temporary file path as follows:

  1. The path specified by the TMP environment variable.
  2. The path specified by the TEMP environment variable, if TMP is not defined.
  3. The current directory, if both TMP and TEMP are not defined.

Solution 5

Function GetTempPath will return a path with a short name,eg: C:\Users\WDKREM~1\AppData\Local\Temp\.

To get a full temp path name,use GetLongPathName subsequently.

Share:
46,706

Related videos on Youtube

Chris
Author by

Chris

Updated on July 09, 2022

Comments

  • Chris
    Chris almost 2 years

    How I can get the user's temp folder path in C++? My program has to run on Windows Vista and XP and they have different temp paths. How I can get it without losing compatibility?

    • Richard Corden
      Richard Corden over 14 years
      If you're only interested in windows solutions you should place that in your question title.
    • kayleeFrye_onDeck
      kayleeFrye_onDeck over 5 years
      Please consider changing the accepted answer to f-roche's, stackoverflow.com/a/51702008/3543437
  • JaredPar
    JaredPar over 14 years
    You should link to an MSDN documentation as opposed to copy and apsting the contents
  • endorphin
    endorphin over 14 years
    I'd actually appreciate both the info AND the link. The problem with links is that they rot over time.
  • Rob Kennedy
    Rob Kennedy over 14 years
    -1 for giving no indication that it's a quotation, for not citing the source of the quotation, and for pasting out-of-date information.
  • Donald Duck
    Donald Duck over 6 years
    This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post.
  • kayleeFrye_onDeck
    kayleeFrye_onDeck over 5 years
    You should be able to just use GetTempPath instead of GetTempPathW or GetTempPathA. You're encouraged to not use WinAPIs with the A and W contexts directly, as it's supposed to detect if your project is ANSI or not and use the correct one based off of that. At the very least it will make your code more robust.
  • kayleeFrye_onDeck
    kayleeFrye_onDeck over 5 years
    Won't that only work on Windows if it's in English or some set of Latin-character languages?
  • kayleeFrye_onDeck
    kayleeFrye_onDeck over 5 years
    std::filesystem::temp_directory_path().wstring() works like a charm!
  • kayleeFrye_onDeck
    kayleeFrye_onDeck over 5 years
    Well... kind of. I was hoping it would return whatever TEMP was set to, but it does more behind the scenes (but for your own good). For example, I've got a UWP Unit Test app, and it returns this instead: L"C:\\Users\\user name\\AppData\\Local\\Packages\\$(GUID)\\AC\\Temp\\$(FileNam‌​e)" Which is the more useful of the two possibilities, seeing as a UWP app wouldn't let you write directly to whatever is set to TEMP in your env-vars with something like fwrite, which I manually verified is in fact the case.
  • kayleeFrye_onDeck
    kayleeFrye_onDeck about 5 years
    This will usually return C:\Windows\Temp for Win32 apps and the temporary storage location for Windows Store Apps for AppContainers, and is also what std's filesystem temp_directory_path() api will return. Personally, I'd rather use the std instead of mucking around directly with WinAPIs, but a mature <filesystem> wasn't around when this was answered initially.
  • Remy Lebeau
    Remy Lebeau almost 3 years
    GetTempPath() has been around a lot longer than W2K. It existed in Win95.