Thread: using getenv correctly

  1. #1
    Registered User
    Join Date
    Jan 2009

    using getenv correctly

    Hi all, I am writing my first programs to gain a better understanding of environment variables.
    So far I have written this - and it compiles with no errors and returns successfully returns a value for the 'PATH'. As seen below:

    #include <stdlib.h>
    #include <stdio.h>
    int main()
          char *env = getenv("PATH");
          if (env)
                printf("\nvalue of PATH is: %s\n", env);
          return 0;
    However, if change 'PATH' to another environment variable as stated on this list:
    such as 'TIME' , then 'NULL' is returned. Basically my question is theory only and I want to know why some environment variables are returned and others are not?. Also I have only a basic understanding of how to use the terminal correctly, so are there commands from the terminal that will show me what environment variables are running?

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    Try with TEMP or TMP

    I can imagine TIME (and DATE and RANDOM) being a pseudo-variable evaluated by the shell at the moment you use it.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Apr 2008
    This is more simple than you think: the environment variables are strings "name=value" copied into the process stack when you run it, nothing more. You can get the entire list by walking the 'environ' variable (this is a global pointer to the array of environment variable your process got). You can also see your current env. var in a shell by typing 'env'.

    from <unistd.h>:
    /* NULL-terminated array of "NAME=VALUE" environment variables. */
    extern char **environ;

  4. #4
    Registered User
    Join Date
    Jan 2009

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Did I Install the Platform SDK Correctly?
    By bengreenwood in forum C++ Programming
    Replies: 7
    Last Post: 07-14-2008, 09:33 AM
  2. strange error -- COM DLL is not installed correctly?
    By George2 in forum C# Programming
    Replies: 0
    Last Post: 07-16-2007, 08:32 AM
  3. QUERY_STRING in CGI with a C/C++ Program
    By stovellpaul in forum C++ Programming
    Replies: 5
    Last Post: 10-03-2002, 12:51 AM
  4. Why does this not read in correctly?
    By bluebob in forum C Programming
    Replies: 9
    Last Post: 04-19-2002, 09:17 AM
  5. Replies: 1
    Last Post: 11-19-2001, 04:45 PM