1、getenv函数
获取环境变量的值
man 3 getenv
#include<stdlib.h>
char *getenv(const char*name);
DESCRIPTION
The getenv() function searches the environment list to find theenvironment variable name, and returns a pointer to the corresponding valuestring.
成功返回环境变量的值,失败返回NULL。
2、setenv函数和unsetenv函数
命令查看: man 3 setenv
NAME
setenv - change or add an environmentvariable //改变或添加一个环境变量
SYNOPSIS
#include <stdlib.h>
int setenv(const char *name, const char*value, int overwrite);
int unsetenv(const char *name);
overwrite参数:
非0表示覆盖原有环境变量,0表示不覆盖。
返回值:
The setenv() function returns zero onsuccess, or -1 on error, with errno set to indicate the cause of the error.
The unsetenv() function returns zero on success, or -1 on error,with errno set to indicate the cause of the error.
可见,两个函数都是成功返回0,失败返回-1,并记录errno信息。
测试程序:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char* val;
const char* name ="ABC";
//获取ABC环境变量的值
val = getenv(name);
printf("No.1 %s=%s\n", name, val);
//覆盖写入环境变量
setenv(name, "I amsure of that I will get it", 1);
printf("No.2%s=%s\n", name, val);
val = getenv(name);
printf("No.3%s=%s\n", name, val);
//删除一个环境变量
int ret =unsetenv("ABC");
printf("ret =%d\n",ret);
val = getenv(name);
printf("No.3 %s=%s\n",name, val);
return 0;
}
编译执行:
yu@ubuntu:~/cplusplus/hjbl_环境变量$ gcc env_opt.c -o env_opt
yu@ubuntu:~/cplusplus/hjbl_环境变量$ ./env_opt
No.1 ABC=(null)
No.2 ABC=(null)
No.3 ABC=I am sure of that I will get it
ret = 0
No.3 ABC=(null)