DEV Community

Naman Tamrakar
Naman Tamrakar

Posted on • Edited on

4 2

Ways to get and set environment variables in C

In this article, I will discuss some of the most simple ways to access environment variables in C language programming.

Approach 1

In this method, we simply used the environ variable by extending it using the extern keyword.

Code

#include <stdio.h>

// https://man7.org/linux/man-pages/man7/environ.7.html
extern char **environ;

int main(int argc, char **argv) {
    // list out all the environment variables
    for (int i=0; environ[i]!=NULL; i++) {
        printf("%d: %s\n", i, envp[i]);
    }

    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Check out environ man page for more info.

Approach 2

Most of the students don't know that the main function can also receive a third argument which is nothing but the array of environment variables.

NOTE: The third argument may not support all compilers. But it should work on the latest compiler versions.

Code

#include <stdio.h>

int main(int argc, char **argv, char **envp) {
    // list out all the environment variables
    for (int i=0; envp[i]!=NULL; i++) {
        printf("%d: %s\n", i, envp[i]);
    }

    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Approach 3

In this method, we use the getenv and setenv functions defined

getenv takes one argument which is the environment variable name and returns a null-terminated char pointer. If the passed name does not exist, it returns NULL.

setenv takes three arguments. The first one is the environment variable name, the second is its value and the third one is an int flag which if non-zero overwrites the already existing environment variable with the same name.

NOTE: setenv doesn't set the environment variable permanently but for the current process and its child process only. It means setenv the environment variables are visible only in the current process and its child ones.

Check out some other functions like clearenv, and putenv in man page for more operations.

Code

#include <stdio.h>
#include <stdlib.h> // setenv, getenv

int main(int argc, char **argv) {
    char *user = getenv("USER"),
        *hosttype = getenv("HOSTTYPE"),
        *hostname = getenv("HOSTNAME");
    printf("USER: %s\n", user ? user : "null");
    printf("HOSTTYPE: %s\n", hosttype ? hosttype : "null");
    printf("HOSTNAME: %s\n", hostname ? hostname : "null");

    setenv("USER", "namantam1", 1);
    printf("updated USER: %s\n", getenv("USER"));

    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Output

USER: naman
HOSTTYPE: x86_64
HOSTNAME: null
updated USER: namantam1
Enter fullscreen mode Exit fullscreen mode

Application

  • We can set log verbosity based on the environment variable.
  • One can set the environment variable in the parent process and access the same in its child process. Check out this article to know how to clone the current process into a child process.

❤️Thank you so much for reading this article. I'm a passionate engineering student learning new things so If you find any mistakes or have any suggestions please let me know in the comments.

Also, consider sharing and giving a thumbs up If this post helps you in any way.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more