为了程序的可移植性,操作环境变量时建议用C语言库中的函数,在Windows 平台里不要用Windows的API来操作环境变量。
C语言操作环境变量有 getenv putenv setenv和unsetenv等函数,现在一一说明如下:
1、getenv函数
头文件:#include<stdlib.h>
函数原型: char * getenv(const char* name);
函数说明:getenv()用来取得参数name环境变量的内容。
函数参数:name为环境变量的名称,如果该变量存在则会返回指向该内容的指针。环境变量的格式为name=value。
返回值:若环境变量存在,返回环境变量值的指针,否则返回NULL。
#include <stdlib.h>
#include <stdio.h>
int main()
{
char* path = NULL;
if((path = getenv("PATH")))
printf("PATH= %s", path);
return 0;
}
2、putenv函数
头文件:#include<stdlib.h>
函数原型: int putenv(const char* str);
函数说明:putenv用来改变或者增加环境变量的内容
参数:str的格式为name=value,若环境原先存在,则环境变量值会依参数str改变,若不存在,则增加该环境变量
返回值:成功返回0,错误返回-1.
#include <stdlib.h>
#include <stdio.h>
int main()
{
char* path = NULL;
if((path = getenv("JAVA_HOME")))
printf("JAVA_HOME= %s", path);
putenv("JAVA_HOME=/java");
if((path = getenv("JAVA_HOME")))
printf("JAVA_HOME= %s", path);
return 0;
}
3、setenv函数
头文件:#include<stdlib.h>
函数原型: int setenv(const char* name, const char* value, int overwrite)
函数说明:setenv用来改变或者增加环境变量
参数:name为环境变量名称字符串。 value则为变量内容,overwrite用来决定是否要改变已存在的环境变量。如果overwrite不为0,而该环境变量原已有内容,则原内容会被改为参数value所指的变量内容。如果overwrite为0,且该环境变量已有内容,则参数value会被忽略。
返回值:成功返回0,错误返回-1.
#include <stdlib.h>
#include <stdio.h>
int main()
{
char* path = NULL;
if((path = getenv("JAVA_HOME")))
printf("JAVA_HOME= %s", path);
setenv("JAVA_HOME", "/data/java", 1);
if((path = getenv("JAVA_HOME")))
printf("JAVA_HOME= %s", path);
return 0;
}
4、unsetenv函数
头文件:#include<stdlib.h>
函数原型: int unsetenv(const char* name)
函数说明:删除name环境变量的定义,即使不存在也不会出错
参数:name为环境变量名称字符串。
返回值:成功返回0,错误返回-1.
#include <stdlib.h>
#include <stdio.h>
int main()
{
char* path = NULL;
unsetenv("JAVA_HOME");
path = getenv("JAVA_HOME");
printf("JAVA_HOME= %s", path);
return 0;
}