how to export integer value to the environment variable in c
c, environment-variables
Solution
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);
Problem
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; } ```