Linux环境变量getenv setenv unsetenv操作
在linux操作系统中,可以通过man来进行相关函数的查看 eg: man setenv
1、setenv 设置环境变量
//函数原型
int setenv(const char *name, const char *value, int overwrite);
1.return value 返回值
setenv() function returns zero on success, or -1 on error, with er‐rno set to indicate the cause of the error.
The unsetenv() function returns zero on success, or -1 on error, witherrno set to indicate the cause of the error.
2、getenv 获取环境变量
//函数原型
char *getenv(const char *name);
2.return value 返回值
The getenv() function returns a pointer to the value in the environment, or NULL if there is no match.
3、unsetenv 删除环境变量
//函数原型
int unsetenv(const char *name);
3.return value 返回值
The setenv() function returns zero on success, 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.
实验测试
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ENV_NAME "LINUX"
int main(void)
{
char* val;
//获取Linux环境变量的值
val = getenv(ENV_NAME);
printf("No.1 %s=%s\n", ENV_NAME, val);
//覆盖写入环境变量
setenv(ENV_NAME, "I Can Get It", 1);
printf("No.2 %s=%s\n", ENV_NAME, val);
val = getenv(ENV_NAME);
printf("No.3 %s=%s\n", ENV_NAME, val);
//删除一个环境变量
int ret =unsetenv(ENV_NAME);
printf("ret =%d\n",ret);
val = getenv(ENV_NAME);
printf("No.3 %s=%s\n",ENV_NAME, val);
return 0;
}