C library - getenv() function



The C stdlib library getenv() function searches for the environment string pointed to by name in the list of environment variables associated with the current process. It finds a match by the name we provided. If it finds a match, it returns a pointer to the C string that contains the value of that environment variable.

A environment variable is user-definable value that can affect the running behaviour of a computer process.

Syntax

Following is the C library syntax of the getenv() function −

char *getenv(const char *name)

Parameters

This function accepts a single parameter −

  • name− It represents a C string containing the name of the specified variable.

Return Value

This function returns a null-terminated string if an environment variable exists; otherwise, it returns NULL.

Example 1

In this example, we create a basic c program to demonstrate the use of getenv() function.

#include <stdlib.h>
#include <stdio.h>

int main() {
   // Name of the environment variable (e.g., PATH)
   const char *name = "PATH";
   // Get the value associated with the variable
   const char *env_p = getenv(name);
   if(env_p){
      printf("Your %s is %s\n", name, env_p);
   }
   return 0;
}

Output

Following is the output −

Your PATH is /opt/swift/bin:/usr/local/bin/factor:/root/.sdkman/candidates/kotlin/current/bin:/usr/GNUstep/System/Tools:/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/usr/local/scriba/bin:/usr/local/smlnj/bin:/usr/local/bin/std:/usr/local/bin/extra:/usr/local/fantom/bin:/usr/local/dart/bin:/usr/libexec/sdcc:/usr/local/icon-v950/bin:/usr/local/mozart/bin:/opt/Pawn/bin:/opt/pash/Source/PashConsole/bin/Debug/:.:/root/.sdkman/candidates/kotlin/current/bin:/usr/bin:/sbin:/bin

Example 2

Let's create another example, we retrieve the value of the path "tutorialspoint" environment variable. If it exists. Otherwise we display "Environment Variable doesn't exist!".

#include <stdlib.h>
#include <stdio.h>
int main() {
   // name of the environment
   const char* env_variable = "tutorialspoint";
   // Retrieve the value
   char* value = getenv(env_variable); 

   if (value != NULL) {
      printf("Variable = %s \nValue %s", env_variable, value);
   } else {
      printf("Environment Variable doesn't exist!");
   }
   return 0;
}

Output

Following is the output −

Environment Variable doesn't exist!
Advertisements