C/C++ 获取系统环境变量,其实是很简单的。
下面是一个单纯c语言获取的方式.:
#include #include intmain(void)
{char*pathvar;
pathvar = getenv("PATH");
printf("pathvar=%s",pathvar);return0;
注:getenv() 是在stdlib中定义的,当然我们也可以在c++中,通过 #include<cstdlib> std:getenv()来使用它。若考虑可移植性,这两种方式都是可以优先使用的。
在windows环境下,我们也可以用WINAPIGetEnvironmentVariable()来获取某个环境变量的值。
我们还有两种方式,可以列出当前设定的所有的环境变量的值。
1. envp
#include#includeintmain(intargc,char**argv,char** envp)
char** env;
for(env = envp; *env !=0; env++)
char* thisEnv = *env;
printf("%s\n", thisEnv);
注:这里需要注明的是,关于envp,如果考虑程序的可移植性的话,最好不要用envp用为main函数的第三个参数。
因为他是一种常见的unix系列系统的扩展。 envp 是一个以null结尾的字符串数组,在MicrosoftC++中可以使用。如果你用的是wmain,可以你wchar_t 代替char来标识它。
虽然是一种常见的扩展,但并不是所有的系统中都有这种扩展,所以在考虑程序的可移植性的时候最好不要使用他。你如果感觉自学C/C++语言有困难的话,我本身是一个C/C++出身的程序员,我整理了一些学习C语言的视频在Q,关于C/C++编程学习,--78④1; 43后--133。
因为在 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.
2.extern char **environ
#include #include externchar**environ;intmain(intargc,char*argv[])
char**p = environ;
while(*p != NULL)
printf("%s (%p)\n", *p, *p);
*p++;
return0;
这里同样需要说明的是,extern char **environ.在Posix中是在中声明的。
但是在实践中,考虑最好还是使用getenv()函数来取得相关的环境变量。