linux环境编程-环境变量&打印环境变量

在shell编程主题中,我们已经大致的介绍过 环境变量和本地变量啦

我们今天来具体的介绍介绍,那环境变量到底是什么呢?

先来个视频了解一下  是谁

是我

一.环境变量含义&特征

环境变量是指 操作系统中用来指定操作系统运行环境的一下参数

1)特征:

  1. 字符串
  2. 有统一的格式: 名=值[:值]
  3. 值用来描述进程的环境信息

2)使用形式:与命令行参数类似

3)存储形式:与命令行参数类似,char* []数组,数组名 environ, 内部存储字符串, NULL做为哨兵

4)加载位置:与命令行参数类似,位于用户区,  高于stack区域 的起始位置

扫描二维码关注公众号,回复: 11713745 查看本文章

5)引入环境变量表:必须声明 环境变量  extern char** environ;

代码Demo

#include <iostream>

extern char **environ;

int
main(int argc, char *argv[])
{
	int i;
	for(i=0; environ[i]; i++){
		printf("%s\n", environ[i]);
	}
	return 0;
}

 ./echoPath 效果如下

 下面我们在介绍一下两个关于 环境变量的函数

char *getenv(const char* name) ; 获取名字为name的环境变量

int setenv(const char* name, const char* value, int overwrite);  // return 0(success), -1(err)

        overwrite   1:覆盖原来的环境变量

                          0:不覆盖,改参数常用于设置新的环境变量

#include <iostream>
#include <stdlib.h>

using namespace std;

int
main(int argc, char* argv[])
{
	char *path_value = NULL;
	const char* path_name = "ABC";
	if(path_value = getenv(path_name)){
		printf("name: %s, value:%s \n", path_value, path_value);
	}else{
		printf("the %s path is not exist \n", path_name);
	}
	int   ret = setenv(path_name, "yyyy-mm-dd", 1);
	if(ret == 0){
		printf("set environment success \n");
	}else{
		cerr << "setenv error" << endl;
	}

	if(path_value = getenv(path_name)){
		printf("name: %s, value:%s \n", path_value, path_value);
	}else{
		printf("the %s path is not exist \n", path_name);
	}

	#if 1
		ret = unsetenv(path_name);
		if(ret == 0){
			cout << " unsetenv success" << endl;
			if(path_value = getenv(path_name)){
				printf("name: %s, value:%s \n", path_value, path_value);
			}
		}else{
			cerr << "unsetenv error" << endl;
		}
		
	#endif 

	return 0;
}

运行效果:

猜你喜欢

转载自blog.csdn.net/qq_44065088/article/details/108529902