1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > Linux操作环境变量 getenv函数 setenv函数 unsetenv函数使用

Linux操作环境变量 getenv函数 setenv函数 unsetenv函数使用

时间:2023-08-10 09:28:50

相关推荐

Linux操作环境变量 getenv函数 setenv函数 unsetenv函数使用

1、getenv函数

获取环境变量的值

man 3 getenv#include<stdlib.h>char *getenv(const char*name);DESCRIPTIONThe getenv() function searchesthe environment list to find theenvironment variable name, and returns a pointer to the corresponding valuestring.

成功返回环境变量的值,失败返回NULL。

2、setenv函数和unsetenv函数

命令查看: man 3 setenv

NAMEsetenv - 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.Theunsetenv() function returnszero 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_optyu@ubuntu:~/cplusplus/hjbl_环境变量$ ./env_opt No.1 ABC=(null)No.2 ABC=(null)No.3 ABC=I am sure of that I will get itret = 0No.3 ABC=(null)

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。