getenv获取环境变量值的函数;
setenv改变或者添加环境变量函数;
unsetenv 取消环境变量;
(可以在终端上man 函数名来获取详细的函数信息)
#include<stdio.h> #include<stdlib.h> #include<string.h> int main() { char *val; const char *name = "ABD"; val = getenv(name); //获取name的环境变量值 printf("1,%s = %s ",name,val); setenv(name, "haha-day-and-night",1); //设置name的环境变量值为haha-day-and-night val = getenv(name); printf("2,%s = %s ",name,val); #if 0 int ret = unsetenv("ABCDEFG"); printf("ret = %d ",ret); val = getenv(name); printf("3,%s = %s ",name,val); #else int ret = unsetenv("ABD"); //取消环境变量name的值 printf("ret = %d ",ret); val = getenv(name); printf("3,%s = %s ",name,val); #endif return 0; }
运行结果:
ubuntu1604@ubuntu:~/wangqinghe/C/20190805$ gcc setenv.c -o setenv
ubuntu1604@ubuntu:~/wangqinghe/C/20190805$ ./setenv
1,ABD = (null)
2,ABD = haha-day-and-night
ret = 0
3,ABD = (null)
把if 0 改为 1
运行结果:
ubuntu1604@ubuntu:~/wangqinghe/C/20190805$ gcc setenv.c -o setenv
ubuntu1604@ubuntu:~/wangqinghe/C/20190805$ ./setenv
1,ABD = (null)
2,ABD = haha-day-and-night
ret = 0
3,ABD = haha-day-and-night
没有ABCDEFG这个环境变量,删除它时,是不会报错的。
但是如果把 int ret = unsetenv("ABCDEFG");
改为 int ret = unsetenv("ABD="); 这种时,它会报错。
运行结果:
ubuntu1604@ubuntu:~/wangqinghe/C/20190805$ ./setenv
1,ABD = (null)
2,ABD = haha-day-and-night
ret = -1
3,ABD = haha-day-and-night