📅  最后修改于: 2020-09-25 08:50:46             🧑  作者: Mango
如果传递给getenv() 函数的环境变量不在环境列表中,则它将返回空指针。
char* getenv( const char* env_var );
此函数在
getenv() 函数返回:
#include
#include
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