Click here to Skip to main content
15,889,931 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C++
char* TempPath()
{
     char *Buffer;
     DWORD dwRet;
     dwRet   = GetTempPath(0,NULL);
     if( dwRet == 0 )
     {
         printf("GetCurrentDirectory failed (%d)\n", GetLastError());
         return NULL;
     }
     Buffer = (char *)malloc(sizeof(char)*dwRet);
     memset(Buffer,0,dwRet*sizeof(char));
     GetTempPath(dwRet,Buffer);
     return add_slash(Buffer);
}

	char* purPath = TempPath();
	sprintf(purPath,"%sTest.txt",purPath);
	fout = fopen(purPath, "r");


when i build the code to exe,and double click exe to run application,it throw error as below:
C#
Try to read or write protected memory. This usually indicates that other memory is corrupt


why?
i want to hide Test.txt file path,so use the system temp file to store filepath.
how can i achieve the same purpose and not throw memory error?

What I have tried:

if i change the temp file path to debug dirctory,it runs ok.
Posted
Updated 13-Jun-16 19:55pm
v2

Have a look at this example: Creating and Using a Temporary File (Windows)[^]
Look at this line:
C#
 //  Gets the temp path env string (no guarantee it's a valid path).
dwRetVal = GetTempPath(MAX_PATH,          // length of the buffer
                       lpTempPathBuffer); // buffer for path

lpTempPathBuffer

is where the temporary path name is placed.
Now -- You must also allocate sufficient space for the filename in your buffer else this line will fail:
C++
sprintf(purPath,"%sTest.txt",purPath);

You are copying the buffer plus some extra bytes into the original buffer.
That is why in the example the buffer is created as length MAX_PATH.
 
Share this answer
 
v5
Comments
xuyunhai 14-Jun-16 1:27am    
you can try to invoke TempPath method,return correct path.
C++
char* tempPath = TempPath();
char purPath[256];
if(tempPath != NULL)
{
    strcpy(purPath, tempPath);
}
    sprintf(purPath,"%sTest.txt",purPath);
fout = fopen(purPath, "r");
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900