Click to See Complete Forum and Search --> : Windows Temp Dir


SpazzMonkeys
March 2nd, 2007, 01:19 AM
This should be a very simple question, but I can't for the life of me find the answer to it. Quite simply, how can I query where the windows temp directory is?

I'm making a program that will write a batch file in the temp directory when run off my thumb drive. I'm choosing the temp directory because users have access to their own temp directory at my school. Since this is going to go on my thumb drive, it needs to be versatile and not just point to C:\temp or C:\Documents and Settings\User Name\Local Settings\Temp.

So far I've had some success, but with undesirable methods. So far what I've done is use the System function to save them evaluation of %temp% to a text file and then read that in to my variable. This is undesirable for two reasons: One that system is used, because I've read it's a naughty little function, and Two, because it's writing a file to my thumbdrive! (Thumbdrives have a limited lifespan based on the number of writes to it. And this sort of thing can add up over time).


//includes
#include <cstdlib>
#include <iostream.h>
#include <fstream.h>

using namespace std;

int main(int argc, char *argv[])
{
//write temp directory to file
system("echo %temp% > tempDir");

//read in temp directory
ifstream TD("tempDir",ios::in);
string tempDir;
if(TD.is_open())
{
getline(TD, tempDir);
TD.close();
}
//output it
cout << "tempDir is " << tempDir << endl;

system("pause"); //Oops, I did it again, well, it's a dev cpp thing
return EXIT_SUCCESS;
}


So basically, how do I find where the windows temp directory is without writing anything to a file, and hopefully without calling system()?

laasunde
March 2nd, 2007, 01:54 AM
You could try getenv (http://www.cplusplus.com/reference/clibrary/cstdlib/getenv.html) and use "TMP" as input.

humptydumpty
March 2nd, 2007, 02:46 AM
I think you Directly can read it from your environment variables.

Thanx

SpazzMonkeys
March 2nd, 2007, 02:53 AM
You could try getenv and use "TMP" as input.

Thank you so much, that's exactly what I needed! Man, I simply could not find that anywhere. Now I've got it working like a charm (so far).

I think you Directly can read it from your environment variables.

I'm not exactly sure what you mean by that, but just typing in %temp% into my code doesn't work, I tried that before posting here.

SuperKoko
March 2nd, 2007, 04:17 AM
Use GetTempPath (http://msdn2.microsoft.com/en-us/library/aa364992.aspx), I'm pretty sure getenv("TMP") isn't reliable. For example, there are guys that may not have defined this environment variable.