Click here to Skip to main content
15,898,373 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
HI ALL,

Now i am using the getenv() function for getting the environment variable.You can see the example below and find when fun() execute first time str have initialized that value but when we call fun() in second time then str have not initialize full path.. I need ur help, how i get the full path when we call fun() in second time.

C++
#include "stdafx.h"
#include <windows.h>
#include <stdio.h>
#include <string.h>
void fun();
int main ()
{
 fun();
 fun(); 
 return 0;
}
void fun()
{
  char * pch,*val,*str,*str1;
  
  val = "TEMP";
  str = getenv(val);
  str1=str;
  pch = strtok (str1,"\\");
  while (pch != NULL)
  {
    pch = strtok (NULL,"\\");
  }
}


Regards
saurabh agrawal
Posted
Updated 17-Oct-12 2:12am
v2

1 solution

getenv() returns a pointer to an internal environment table. By using strtok(), you are modifying the string in the internal table. To avoid this, you must create a copy of the returned string and use this copy for parsing with strtok(). You may use something like this:
C++
// Allocate memory and copy string
str1 = strdup(str);
// do something with str1 here

// release memory
free(str1);
 
Share this answer
 
Comments
Legor 17-Oct-12 8:23am    
Exactly!
Jochen Arndt 17-Oct-12 8:37am    
Thank you.
CPallini 17-Oct-12 8:29am    
5.
Jochen Arndt 17-Oct-12 8:37am    
Thank you too.

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