logo
Get environment variables in C on linux
The unknown main() parameter
The getenv fonction

Get environment variables in C on linux

The unknown main() parameter

The main can in fact take a parameter, char* env[] which is an array containing all environment variables and ending with a NULL string. A small minimalist example of its use:
#include <stdio.h>
 
int main(int argc, char* argv[], char* env[]){
    int i;
    for(i=0;env[i]!=NULL;i++)
	printf("%s\n",env[i]);
    return 0;
}

The getenv fonction

Getenv which the prototype is the following 'char* getenv (const char* name)' is part of 'stdlib.h'. It allows you to retrieve an environment variable.
#include <stdio.h>
#include <stdlib.h>
 
int main(int argc,char* argv[]) {
    char* user=getenv("USER");
    if(user!=NULL)
	printf("USER='%s'\n",user);
    return 0;
}
Do not hesitate to consult the getenv man page for more information.
Be The First To Comment.

Add a comment:





You can use these HTML tags: <br><a><i><b>