主要有三种方法,都很简单。
1 一个单纯c语言获取的方式
<span style="font-family:Microsoft YaHei;font-size:14px;">#include <stdio.h>
#include <stdlib.h>
int main(){
char *pathvar = getenv("PATH");
printf("pathvar is : %s\n",pathvar);
return 0;
}
</span>
getenv() 是在stdlib中定义的,当然我们也可以在c++中,通过 #include<cstdlib> std:getenv()来使用它.若考虑可移植性,这两种方式都是可以优先使用的
#include <stdio.h>
int main(int argc,char **argv,char **envp){
printf("the 1st envp is : %s\n",envp[0]);
return 0;
}
注:这里需要注明的是,关于envp,如果考虑程序的可移植性的话,最好不要用envp用为main函数的第三个参数.
因为他是一种常见的unix系列系统的扩展. envp 是一个以null结尾的字符串数组,在MicrosoftC++中可以使用.如果你用的是wmain.可以你 wchar_t 代替char来标识它.
虽然是一种常见的扩展,但并不是所有的系统中都有这种扩展,所以在考虑程序的可移植性的时候最好不要使用他.
因为在 C99 Standard 中只有两种合法的Cmian函数定义
a) int main(void)
and
b) int main(int argc, char **argv)
or equivalent
and it allows implementations to define other formats (which can allow a 3rd argument)
c) or in some other implementation-defined manner.
3 extern char **environ
#include <stdio.h>
extern char **environ;
int main(int argc,char **argv){
printf("get envp by environ,the 2nd envp is : %s\n",++*environ);
return 0;
}<span style="color:#ff0000;">
</span>
这里同样需要说明的是,extern char **environ.在Posix中是在<unistd.h>中声明的.详细信息可以参看:http://www.unix.org/single_unix_specification/ 它也是unixsm的,并且在windows中是没有定义的,所以但是在实践中,考虑最好还是使用getenv()函数来取得相关的环境变量.
参考文章:http://www.cnblogs.com/algorithmic/archive/2012/09/23/2698604.html