Coder
Coder

Reputation: 3715

Getting safe temp folder in Windows

I need to get a safe temp folder where I could store temporary files for my application, but so far my research has lead me to conclusion that all approaches I've found are flawed.

The first idea was to use GetTempPath function, but that causes two problems:

In the same post, there is a suggestion to use GetEnvironmentVariable, but this seems a dangerous function to me (missing TMP & TEMP envvars for instance).

Is there a cleaner function I could use? Seems that SHGetKnownFolderPath has no clue what temp folder is.

Upvotes: 4

Views: 1504

Answers (4)

Mark Ransom
Mark Ransom

Reputation: 308196

Your program is probably not the only one to rely on GetTempPath, so it's reasonable to expect it to return a proper writable path. Especially since Windows automatically initializes the TMP and TEMP environment variables for you; someone would have to go to some trouble to override them, and it would be their responsibility to make sure the change did not mess up their system.

I would go ahead and assume GetTempPath works properly, and worry about failures when you try to create the temporary file - there are other errors that might occur at that time that you need to check for anyway.

Upvotes: 3

hlovdal
hlovdal

Reputation: 28180

According to this answer, Boost's Filesystem library can be used for this.

Upvotes: 0

David Heffernan
David Heffernan

Reputation: 612964

Your first bullet point is the solution. Wrap it up in a method so that you don't duplicate code.

Upvotes: 0

Ferenc Deak
Ferenc Deak

Reputation: 35408

An idea would be to get the path where your application is (GetModuleFileNameEx combined with GetModuleHandle(NULL) and GetCurrentProcess) since this directory cannot be deleted under windows as long as your application is running from it (maybe I'm wrong ...some years ago I couldn't do this :) ) and in this directory create a temporary directory.

Upvotes: 0

Related Questions