2009-05-22 42 views
33

如何在C++中設置環境變量?在C++中設置本地環境變量

  • 他們並不需要堅持過去的程序執行
  • 他們只需要在當前進程可見
  • 偏愛的平臺獨立的,但我的問題只需要在Win32工作/ 64

感謝

回答

45
 
NAME 

     putenv - change or add an environment variable 

SYNOPSIS 

     #include &ltstdlib.h> 

     int putenv(char *string); 

DESCRIPTION 
     The putenv() function adds or changes the value of environment 
     variables. The argument string is of the form name=value. If name does 
     not already exist in the environment, then string is added to the 
     environment. If name does exist, then the value of name in the 
     environment is changed to value. The string pointed to by string becomes 
     part of the environment, so altering the string changes the environment. 

在Win32這就是所謂的_putenv我相信。

另請參閱SetEnvironmentVariable如果您是長期和醜陋的函數名稱的粉絲。

+4

提問者注意 - putenv在Win32中也受支持。 – 2009-05-22 19:16:45

+19

我們可以請使用適當的C++頭名稱嗎? 是合適的(是的,我知道......這是我的掛斷)。 – 2009-05-22 19:18:11

+4

這是C作爲上帝的旨意。 – alamar 2009-05-22 19:19:05

3

我不是積極的環境變量是你所需要的,因爲它們不會在程序運行之外使用。無需使用操作系統。

你可能最好有一個singleton類或一個包含所有這些值的名稱空間,並在啓動程序時對它們進行初始化。

-2
#include<stdio.h> 
#include<unistd.h> 
#include<stdlib.h> 
#include<string.h> 
    main(int argc,char *argv[]) 
    { 

    char *var,*value; 
     if(argc==1||argc>3) 
     { 
     fprintf(stderr,"usage:environ variables \n"); 
     exit(0); 
     } 
    var=argv[1]; 
    value=getenv(var); 
    //--------------------------------------- 
     if(value) 
     { 
     printf("variable %s has value %s \n",var,value); 
     } 
     else 
     printf("variable %s has no value \n",var); 
     //---------------------------------------- 
     if(argc==3) 
     { 
     char *string; 
     value=argv[2]; 
     string=malloc(strlen(var)+strlen(value)+2); 
      if(!string) 
      { 
      fprintf(stderr,"out of memory \n"); 
      exit(1); 
      } 
      strcpy(string,var); 
      strcat(string,"="); 
      strcat(string,value); 
      printf("calling putenv with: %s \n",string); 
      if(putenv(string)!=0) 
      { 
      fprintf(stderr,"putenv failed\n"); 
      free(string); 
      exit(1); 
      } 
         value=getenv(var); 
      if(value) 
       printf("New value of %s is %s \n",var,value); 
      else 
      printf("New value of %s is null??\n",var); 
     }  
     exit(0); 

    }//----main 





/* commands to execure on linux compile:- $gcc -o myfile myfile.c 
         run:- $./myfile xyz 
              $./myfile abc 
              $./myfile pqr 
*/