How to get a temporary folder and set a temporary file path?

How to get a temporary folder and set the path to the temp file? I tried the code below, but it has an error. Thank you very much!

TCHAR temp_folder [255]; GetTempPath(255, temp_folder); LPSTR temp_file = temp_folder + "temp1.txt"; //Error: IntelliSense: expression must have integral or unscoped enum type 
+4
source share
2 answers

This code adds two pointers.

 LPSTR temp_file = temp_folder + "temp1.txt"; 

It does not merge strings and does not create any storage for the desired string that you want.

For C-style strings, use lstrcpy and lstrcat

 TCHAR temp_file[255+9]; // Storage for the new string lstrcpy( temp_file, temp_folder ); // Copies temp_folder lstrcat( temp_file, T("temp1.txt") ); // Concatenates "temp1.txt" to the end 

Based on the documentation for GetTempPath , it would be wise to replace all 255 events in your code with MAX_PATH+1 .

+3
source

You cannot add two arrays of characters together and get meaningful results. These are pointers, not a class like std :: string, which provides such useful operations.

Create a large enough TCHAR array and use GetTempPath, then use strcat to add the file name to it.

 TCHAR temp_file [265]; GetTempPath(255, temp_file); strcat(temp_file, "temp1.txt"); 

Ideally, you should also check the GetTempPath result for failure. As far as I can see from the documentation associated with the other answer, the most likely cause of the failure is that the specified path variable is too small. Use MAX_PATH + 1 + 9 as recommended there.

+1
source

All Articles