C/C++ 获取系统环境变量方法.

C/C++ 获取系统环境变量,其实是很简单的.

下面是一个单纯c语言获取的方式. 

#include <stdlib.h>
#include <stdio.h>

int main(void)
{
char *pathvar;
pathvar = getenv("PATH");
printf("pathvar=%s",pathvar);
return 0;
}

注: getenv() 是在stdlib中定义的,当然我们也可以在c++中,通过 #include<cstdlib> std:getenv()来使用它.若考虑可移植性,这两种方式都是可以优先使用的.

在windows环境下,我们也可以用WINAPI GetEnvironmentVariable() 来获取某个环境变量的值. 


我们还有两种方式,可以列出当前设定的所有的环境变量的值.

1. envp

#include<stdio.h>
#include<stdlib.h>

int main(int argc, 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来标识它.

虽然是一种常见的扩展,但并不是所有的系统中都有这种扩展,所以在考虑程序的可移植性的时候最好不要使用他.

因为在 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 <stdio.h>
#include <unistd.h>
extern char **environ;
int main(int argc, char *argv[])
{
        char **p = environ;
        while (*p != NULL)
        {
                printf("%s (%p)\n", *p, *p);
                *p++;
        }
        return 0;
}

 这里同样需要说明的是,extern char **environ.在Posix中是在<unistd.h>中声明的.详细信息可以参看:http://www.unix.org/single_unix_specification/

 他也是unixsm的,并且在windows中是没有定义的,所以但是在实践中,考虑最好还是使用getenv()函数来取得相关的环境变量.

  

posted on 2012-09-23 00:23  algorithmic  阅读(52513)  评论(3编辑  收藏  举报

导航