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()函數來取得相關的環境變量.

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM