Alex
Alex

Reputation: 639

How to use environment variable in a C program

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.

Upvotes: 63

Views: 93810

Answers (5)

Kunal Demla
Kunal Demla

Reputation: 11

Another way could be to use the global variable environ.

#include <stdio.h>

extern char** environ;
void main(int argc, char* argv[])
{
    int i=0;
    while(environ[i]!=NULL){
        printf("%s\n",environ[i++]);
    }
}

Upvotes: -2

user3334059
user3334059

Reputation: 507

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

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

int main()
{
    printf("test\n");

    const char* s = getenv("PATH");

    // If the environment variable doesn't exist, it returns NULL
    printf("PATH :%s\n", (s != NULL) ? s : "getenv returned NULL");

    printf("end test\n");
}

Upvotes: 22

Andrew Domaszek
Andrew Domaszek

Reputation: 671

On windows, you would use GetEnvironmentVariable.

#include <stdio.h>
#include <winbase.h>
int main(int argc, char *argv[])
{
    TCHAR buff[100] = T("");
    DWORD resultLengthInCharacters = GetEnvironmentVariable(T("USERDOMAIN"), buff, 100);

    if (resultLengthInCharacters > 0 && resultLengthInCharacters < 100) {
        _tprintf(T("USERDOMAIN: %s\n"), buff);
    } else if ( resultLengthInCharacters > 100) {
        _tprintf(T("USERDOMAIN too long to store in buffer of length 100, try again with buffer length %lu\n"), resultLengthInCharacters);
    } else {
        // Error handling incomplete, should use GetLastError(),
        // but typically:
        _tprintf(T("USERDOMAIN is empty or not set in the Environment\n"));
    }
    return 0;
}

But if you are trying to get a standard path variable, you should use the SHGetFolderPath function with the right CSIDL variable (like from this question: How do I get the application data path in Windows using C++?)

Upvotes: 1

Danijel
Danijel

Reputation: 8608

getenv:

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

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

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

    return 0;
}

Upvotes: 12

ameyCU
ameyCU

Reputation: 16607

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

Upvotes: 50

Related Questions