Skip to main content

Getting Env Vars in C

·202 words·1 min· 0eafdc7

I was working on a simple c programm and I wanted to access the current users home directory via the $HOME enviroment variable. Of course I googled something like: “How to get home dir in C”, “Linux home dir in C”, …, but really nothing useful or practical showed up. Just some weired work arounds. I was kinda confused, because I cant surley be to first person to do something like this.

Solution
#

I browsed through my local man pages and found something, that might just do the trick for me:

man 3 getenv

Great! A function in the stdlib.h header allows me to access the current enviroment variables.
So I wrote a little test code to check it out:

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

int main()
{
    //  Return values for getenv()
    //      1) Set variable: returns pointer
    //      2) Unset variable: returns NULL
    //      3) Unable to access: returns NULL
	const char *home = getenv("HOME");

	if(home != NULL)
	{
		printf("Current user $HOME is at %s\n", home);
	}
	else
	{
		printf("Unable to getenv()\n");
	}

	return 0;
}

Running the executable after compiling:

etoth@ERIK-LAPTOP > ./01-getenv-homedir     
Current user $HOME is at /home/etoth
etoth@ERIK-LAPTOP > sudo ./01-getenv-homedir
Current user $HOME is at /root
Erik Tóth
Author
Erik Tóth