2009-05-22 19 views
33

¿Cómo configuro una variable de entorno en C++?Establecer variables de entorno local en C++

  • No necesitan persistir la ejecución del programa pasado
  • Sólo tienen que ser visibles en el proceso actual
  • La preferencia por una plataforma independiente, pero para mi problema sólo tiene que trabajar en Win32/64

Gracias

Respuesta

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. 

en Win32 se llama _putenv creo.

Consulte SetEnvironmentVariable también si es fanático de los nombres de funciones largas y feas.

+4

Nota para la persona que pregunta: putenv también es compatible con Win32. –

+19

¿Podemos usar nombres de cabecera C++ adecuados? es apropiado (sí, lo sé ... es un problema mío). –

+4

Es C como el Señor Dios quiso. – alamar

3

No soy positivo Las variables de entorno son lo que necesita, ya que no se van a usar fuera de esta ejecución del programa. No es necesario contratar el sistema operativo.

Puede que sea mejor tener una clase única o un espacio de nombres que contenga todos estos valores, e inicializarlos cuando inicie el programa.

+0

Solo serán visibles para los procesos hijos, y putenv() generalmente no necesita hablar con el sistema operativo en absoluto. – RBerteig

-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 
*/ 
+8

¿Cómo responde este código a la pregunta? ¿Por qué has compartido esto con nosotros? –

+0

Espero que la respuesta consista en (1) un archivo de inclusión y (2) una sola línea de código. Y tal vez una biblioteca con la que debo vincularme. – notlesh

+0

notlesh, ¿por qué? También las instrucciones de compilación están ahí. ¿Por qué agregar más archivos? No entiendo por qué esto es rechazado. – Owl

Cuestiones relacionadas