简体   繁体   English

当被问到用户名时,getenv会返回null吗?

[英]getenv returns null when asked for the username?

I want to get the username using the stdlib functio getenv () However I always get NULL here is the code that I have written: 我想使用stdlib函数getenv ()获取用户名但是我总是得到NULL这里是我写的代码:

#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 ? getenv ()返回的值是否取决于您用于编译代码的机器,以及返回值为NULL

On Windows, you'll need to use getenv("USERNAME") . 在Windows上,您需要使用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. USER / USERNAME环境变量不是标准化的,除非您自己设置,否则在Windows上找不到名为USER的环境变量。

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." 这个页面讨论了getenv()的返回值:“带有所请求环境变量值的C字符串,或者如果这样的环境变量不存在则为空指针”。

It looks like your "USER" environment variable is not set. 看起来您的“USER”环境变量未设置。 Does it show up if you type set on the command line? 如果在命令行上键入set ,它会显示吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM