• Uncategorized

About c : How-to-use-environment-variable-in-a-C-program

Question Detail

I need to know a way for use environment variables in the C programming language. How can I use and read them?

For example, read an environment variable or take the value of an environment variable and load it in another variable.

Question Answer

You can use following functions –

char * getenv (const char *name)-returns a string that is the value of the environment variable name.

char * secure_getenv (const char *name)

Read about some more functions here -http://www.gnu.org/software/libc/manual/html_node/Environment-Access.html#Environment-Access

Use the getenv function from stdlib.h. That’s it!


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

int main(int argc, char *argv[])
    char* my_env_var = getenv("MY_ENV_VAR");

        printf("Var found: %s", my_env_var );
        printf("Var not found.");                

    return 0;

You may also like...

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.