View Full Version: Getting the value of enviroment variable

C++ Learning Community > C++ for Linux > Getting the value of enviroment variable


Title: Getting the value of enviroment variable


xdracox - October 3, 2005 08:25 PM (GMT)
How can I get the value of an enviroment variable?

myork - October 3, 2005 09:32 PM (GMT)
CODE
           #include <stdlib.h>
           char *getenv(const char *NAME);



NB. The value returned MUST not be modified or re-used (even though th return type is char*).

It returns NULL if 'NAME' does not exist (or is not set)
Otherwise it returns a C string pointing at the value of the environemnt variable.


CODE
      #include <stdlib.h>

      int setenv(const char *name, const char *value, int overwrite);
      void unsetenv(const char *name);


Here you must be carefull.
The values you pass to setenv() no longer belong to you. They must not be free'ed, deallocated or reused they now belong to the system (this is implementation specific, but so many implmentations behave this way you should be very carefull with this). They can be re-claimed after a call to unsetenv() but not before.


Thus it is not a good idea to do this:

CODE

void setValue()
{
   char buffer[] = "My Env Value";
   setenv("NAME",buffer);
}// at this point buffer is now out of scope and the space will be re-used.



xdracox - October 3, 2005 09:35 PM (GMT)
ok, thanks a lot

C-Man - October 4, 2005 08:11 AM (GMT)
CODE

#include <stdio.h>
int main (int argc,char ** argv,char ** envp)
{
   while (*envp)
       printf ("%s\n",*envp++);  
   return 0;
}

myork - October 4, 2005 01:38 PM (GMT)
QUOTE (C-Man @ Oct 4 2005, 03:11 AM)
CODE
int main (int argc,char ** argv,char ** envp)


Very good as a history lesson.
but not to be encoraged to new programers.


PS. I used to ask this to interviews who though they knew 'C'

C-Man - October 4, 2005 04:19 PM (GMT)
so this is not supported by the standard anymore ? :/

myork - October 5, 2005 01:21 AM (GMT)

I don;t know. Better ask KTC. he holds the standards.




Hosted for free by InvisionFree