2009-05-22 41 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 
*/