2

I have tried below program to export a value to the environment variable. I want to export an integer value to the environment variable. Below program is taking value as "a" instead of 1. How to export integer value to that environment variable.

#include<stdio.h>

void chnge_env_var(int a)
{
    char *name1="ENV_VAR";
    char *val=NULL;
    int status;
    status = putenv("ENV_VAR=a");
    printf("status %d\n",status);
    val = getenv(name1);
    printf("val %s\n",val);
}

int main()
{
    int a=1;
    chnge_env_var(a);
return 0;
}
Alvin
  • 940
  • 2
  • 13
  • 27

1 Answers1

6

The environment can only hold string values. To store an integer you will have to convert it to a string and then store that. When reading it you can then convert the string back to an integer.

int a = 10;
char env_var[20]; // length of 'ENV_VAR=' plus 12
sprintf(env_var, "ENV_VAR=%d", a);
putenv(env_var);

As 'Code Clown' pointed out, snprintf might be used instead if you aren't absolutely sure that the buffer is of the right size:

snprintf(env_var, 20, "ENV_VAR=%d", a);
Tom van der Woerdt
  • 29,532
  • 7
  • 72
  • 105
  • Maybe use snprintf() to prevent future misuse? – aggsol Apr 18 '13 at 12:17
  • 1
    @CodeClown: This is safer: http://stackoverflow.com/questions/69738/c-how-to-get-fprintf-results-as-a-stdstring-w-o-sprintf#69911 –  Apr 18 '13 at 12:21
  • @0A0D: Nice find, thanks. Even though it's not C as required by question. – aggsol Apr 18 '13 at 12:23
  • @TomvanderWoerdt: Tell that to the Mars Lander :) –  Apr 18 '13 at 12:25
  • @0A0D When dealing with strings like these (static string plus an integer), the maximum output buffer size is always known, so using a C++ `std::string` is definitely overkill. When dealing with more complex cases I might agree though. – Tom van der Woerdt Apr 18 '13 at 12:28
  • Whenever I'm trying to use getenv() to check the value, it is giving segmentation fault. How can I check whether that value has exported or not.? – Alvin Apr 18 '13 at 12:46