Sunday 13 November 2011

How can environment variable values be retrieved? in C programming

How can environment variable values be retrieved?

The ANSI C language standard provides a function called getenv() that performs this very task. The getenv() function is simple—you hand it a pointer to the environment string you want to search for, and
it returns a pointer to the value of that variable. The following example code illustrates how to get the PATH
environment variable from C:
#include <stdlib.h>
main(int argc, char ** argv)
{
char envValue[129]; /* buffer to store PATH */
char * envPtr = envValue; /* pointer to this buffer */
envPtr = getenv(“PATH”); /* get the PATH */
printf(“PATH=%s\n”, envPtr); /* print the PATH */
}

If you compile and run this example, you will see the same output that you see when you enter the PATH
command at the DOS prompt. Basically, you can use getenv() to retrieve any of the environment values
that you have in your AUTOEXEC.BAT file or that you have typed at the DOS prompt since booting. Here’s a cool trick. When Windows is running, Windows sets a new environment variable called WINDIR that contains the full pathname of the Windows directory. Following is sample code for retrieving this string:
#include <stdlib.h>
main(int argc, char ** argv)
{
char envValue[129];
char * envPtr = envValue;
envPtr = getenv(“windir”);
/* print the Windows directory */
printf(“The Windows Directory is %s\n”, envPtr);
}

This is also useful for determining whether Windows is running and your DOS program is being run in a DOS shell rather than “real” DOS. Note that the windir string is lowercase—this is important because it is case-sensitive. Using WINDIR results in a NULL string (variable-not-found error) being returned

It is also possible to set environment variables using the _putenv() function. Note, however, that this function is not an ANSI standard, and it might not exist by this name or even exist at all in some compilers. You can do many things with the _putenv() function. In fact, it is this function that Windows uses to create the windir environment variable in the preceding example.

Cross Reference:

XIV.2: How can I call DOS functions from my program?
XIV.3: How can I call BIOS functions from my program?

No comments:

Post a Comment