1

I want to get the username using the stdlib functio getenv ()However I always get NULL here is the code that I have written:

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

 main()
 {

 char *hai;
 printf("The current User name is\n");
 hai="USER";
 printf("%s\n",getenv(hai));


exit(0);
}

Does the value that getenv () returns depends on the machine that you are using to compile your code, and why the value returned is NULL?

user1680944
  • 537
  • 2
  • 13
  • 23

2 Answers2

2

On Windows, you'll need to use getenv("USERNAME"). The USER/USERNAME environment variable is not standardized, and you won't find an environment variable named USER on Windows unless you set it yourself.

rici
  • 234,347
  • 28
  • 237
  • 341
1

This page talks about the return value for getenv(): "A C-string with the value of the requested environment variable, or a null pointer if such environment variable does not exist."

It looks like your "USER" environment variable is not set. Does it show up if you type set on the command line?

kmort
  • 2,848
  • 2
  • 32
  • 54
  • Does it mean that if I am running my code under Windows I need to write "USERNAME" but If I am running it under LINUX I need to specify "USER" right? – user1680944 Feb 06 '14 at 03:53
  • @user1680944 That is correct. You can type `set` in a console/terminal window and see all the environment variables that are currently set. On Windows you'll see "USERNAME", and I believe (though I did not check) that you will see "USER" in Linux. – kmort Feb 06 '14 at 04:00