如果传递给 getenv() 函数的环境变量不在环境变量列表中,它将返回一个空指针。
getenv() 原型
char* getenv( const char* env_var );
该函数定义在 `
getenv() 参数
- env_var: C 字符串,包含环境变量的名称。
getenv() 返回值
getenv() 函数返回
- 由 env_var 表示的环境变量的值。
- 如果环境变量不在环境变量列表中,它将返回一个空指针。
示例:getenv() 函数如何工作?
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
/* A list of possible environment variables*/
const char *env_var[5] = {"PUBLIC","HOME","SESSIONNAME","LIB","SystemDrive"};
char *env_val[5];
for(int i=0; i<5; i++)
{
/* Getting environment value if exists */
env_val[i] = getenv(env_var[i]);
if (env_val[i] != NULL)
cout << "Variable = " << env_var[i] << ", Value= " << env_val[i] << endl;
else
cout << env_var[i] << " doesn't exist" << endl;
}
}
运行程序时,可能的输出是
Variable = PUBLIC, Value= C:\Users\Public HOME doesn't exist Variable = SESSIONNAME, Value= Console LIB doesn't exist Variable = SystemDrive, Value= C:
注意:输出因设备而异。要查看所有环境变量及其值的列表
对于 Windows:在命令提示符中键入 set 然后按 Enter
对于 Linux:在终端中键入 env 然后按 Enter