环境变量
1. 对环境变量的操作的几个库函数
- 每个进程都有一个属于自己的环境变量列表,进程使用这些变量的值去使用系统提供的资源。下面主要说说使用库函数操作进程的环境变量。
1.1 getenv
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/0aff51f3bfc009a27ff2f4d3d86d6f14.png)
1.2 putenv
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/ba7ab8017bcf3933dc3ba77533f38731.png)
1.3 setenv
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/d0248efb33082b471810c77712dc671c.png)
1.4 unsetenv, clearenv
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/d1aa70ac4b8a3bc5d5b6e492b32a91b6.png)
2. 代码示例
#include "t_stdio.h"
#include <stdlib.h>
extern char **environ;
int main(void){
char *p = getenv("caption");
if (p == NULL)
printf("not find ...\n");
else
printf("caption: %s\n", p);
setenv("caption", "shenzhen", 1);
p = getenv("caption");
printf("caption: %s\n", p);
unsetenv("caption");
p=getenv("caption");
printf("caption: %s\n", p);
clearenv();
if(environ==NULL){
printf("clear all ... \n");
}
return 0;
}
$ ./a.out
not find ...
caption: shenzhen
caption: (null)
clear all ...
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void){
char buf[128]="caption=shenzhen";
putenv(buf);
char *p = getenv("caption");
if (p == NULL)
printf("not find ...\n");
else
printf("caption: %s\n", p);
strcpy(buf, "caption=xian");
p = getenv("caption");
if (p == NULL)
printf("not find ...\n");
else
printf("caption: %s\n", p);
}
$ ./a.out
caption: shenzhen
caption: xian