Thursday, May 11, 2006

C++: How to get the Temp Directory

For the currently logged-in user, you can edit the TEMP and TMP folders. In Windows XP, if your right-click on My Computer, go to Properties, go to the Advanced tab, click on Environment Variables, and you can set TEMP and TMP from here.

But what if you are writing a program that needs to create a temporary file? windows.h provides us with the GetTempPath() function used below. The following program was taken from an MSDN coding example.

code to fetch it: [revised]
#include <windows.h>
#include <stdio.h>
#define BUFSIZE 4096

int main(int argc, char* argv[])
{
DWORD dwRetVal;
DWORD dwBufSize=BUFSIZE; // length of the buffer
char lpPathBuffer[BUFSIZE]; // buffer for path

// Get the temp path.
dwRetVal = GetTempPath(dwBufSize, lpPathBuffer);

if (dwRetVal > dwBufSize)
{
printf ("GetTempPath failed with error %d.\n",
GetLastError());
return (2);
}
printf("GetTempPath returned: %s", lpPathBuffer);
return (0);
}
Originally I had included code for Borland C++ Builder code which went and did a manual fetch from the registry, but a reader posted about GetTempPath. I'm more familiar with borland C++ than I am with ms visual studio and windows API commands, so thanks to kicheck for that.

kichik said...
GetTempPath works "on Windows 9x as well and requires a lot less code. It'll also fallback from TMP to TEMP to USERPROFILE to WINDIR in case any of those don't exist."

1 comment:

Anonymous said...
This comment has been removed by a blog administrator.