setenv() 和 unsetenv() 分别用来设置和删除环境变量。函数原型如下:
[C++] 纯文本查看 复制代码
#include <stdlib.h>
int setenv(const char *name, const char *value, int overwrite);
int unsetenv(const char *name);
在 setenv 中,第 1 个参数 name 为要设置的环境变量名;
第 2 个参数 value 为要设置的环境变量的内容。
第 3 个参数 overwrite 的值为 0 或者 非0,当 非0 时表示要以 value 的值覆盖原有的变量值;如果为 0, 则表示保留现有定义。
在 unsetenv 中,只有一个 name 参数,它表示的是要删除变量的定义。
示例代码:
[C++] 纯文本查看 复制代码
#include <stdio.h>
#include <stdlib.h>
int main()
{
if (setenv ("SELDEF", "set_by_setevn_function", 1) != 0) {
perror ("setenv");
exit (EXIT_FAILURE);
}
printf ("Value of $SELDEF:%s\n",getenv("SELDEF"));
if (unsetenv("SELDEF") != 0) {
perror ("unsetenv");
exit (EXIT_FAILURE);
}
if (getenv("SELDEF") == NULL)
printf ("unsetenv successfully\n");
return 0;
}
运行输出:[beyes@SLinux syscall]$ ./setenv
Value of $SELDEF:set_by_setevn_function
unsetenv successfully
和 setenv() 类似的函数是 putenv() 。它们用法基本相同,putenv() 和 getenv() 可参考:http://www.groad.net/bbs/read.php?tid-599.html |