Question

Is it possible to modify an environment variable within a C program. Something like this:

#include <stdlib.h>
int main( void )
{
    system( "echo $VARIABLE" );
    system( "VARIABLE=somethig");
    system( "echo $VARIABLE" );
    return 0;
}
Was it helpful?

Solution 2

setenv(const char *name, const char *value, int overwrite); is the function you need.

e.g. setenv("CONFIG_PATH", "/etc", 0);

From the man page:

DESCRIPTION
The setenv() function adds the variable name to the environment with the value value, if name does not already exist. If name does exist in the environment, then its value is changed to value if overwrite is nonzero; if overwrite is zero, then the value of name is not changed. This function makes copies of the strings pointed to by name and value (by contrast with putenv(3)).

OTHER TIPS

Use setenv() or putenv(). Beware the gotchas with putenv().

Your code as written sets the environment of a new shell interpreter spawned by call to system(). That environment is discarded when system() returns.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top