I am trying to get a users home directory using getenv("$HOME")
, but it is returning NULL. What am I doing wrong?
int main(void)
{
char * path;
path = getenv("$HOME");
printf ("The current path is: %s",path);
return 0;
}
Leave the $
off the environment variable name. When used in the shell the $
is not part of the name, but signals the shell that a variable name follows and it should substitute its value.
getenv("PATH"); // This is what you really want
And, optionally, compile with -Wall
and end up with something like this. (Tested...)
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char *path;
path = getenv("PATH");
if(path)
printf("The current path is: %s\n", path);
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With