当前位置: C语言 -- 标准库 -- <stdlib.h> -- getenv

getenv函数


概要:
#include <stdlib.h>
char *getenv(const char *name);

描述:

该函数在宿主环境提供的环境列表中搜索与参数name指向字符串匹配的字符串。环境名称集和修改环境列表的方法由实现定义。

Windows 10系统中,环境变量可以通过以下方法查询:

控制面板\系统和安全\系统\高级系统设置\高级\环境变量(N)...


getenv函数不需要避免与修改环境列表的其它执行线程的数据竞争。实现应像没有库函数调用getenv函数一样。

ISO/IEC 9899:2018标准还定义了该函数的安全版本getenv_s


参数:
const char *name

指向要搜索的字符串。


返回值:

该函数返回一个指向与匹配列表成员相关联的字符串的指针。程序不能修改指向的字符串,但后续调用getenv函数可能会覆盖该字符串。

如果没有找到参数name指定的字符串,函数返回一个空指针。


范例:
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
/*函数getenv范例*/

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

int main(void)
{
    /*获取计算机名。*/
    char *computerName;

    computerName = getenv("COMPUTERNAME");
    if(computerName!=NULL)
        printf("Computer name: %s", computerName);

    return 0;
}


输出:

Computer name: DESKTOP-FFPQ3NO


相关内容:
system 执行系统命令的函数。