Name

getenv

Synopsis

Obtains the string value of a specified environment variable

#include <stdlib.h>
char *getenv( const char *name );

The getenv() function searches the environment variables at runtime for an entry with the specified name, and returns a pointer to the variable’s value. If there is no environment variable with the specified name, getenv() returns a null pointer.

Your program must not modify the string addressed by the pointer returned, and the string at that address may be replaced by subsequent calls to getenv(). Furthermore, C itself does not define a function to set or modify environment variables, or any list of variable names that you can expect to exist; these features, if available at all, are system-specific.

Example

#define MAXPATH 1024;
char sPath[MAXPATH] = "";
char *pTmp;

if (( pTmp =getenv( "PATH" )) != NULL )
  strncpy( sPath, pTmp, MAXPATH − 1 );           // Save a copy for our use.
else
  fprintf( stderr, "No PATH variable set.\n") ;

See Also

system()

Get C in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.