Reputation: 197
I am trying to understand how setenv() works. The documentation is
setenv (const char *name, const char *value, int overwrite)
I want to be able to edit the environment variable array. For example I want to set
envp[1] = "Hello World"
I am confused by the setenv function though and not sure how to implement in the function. Would the overwrite be the index of the environment array. Would this affect the printing of all the environments like this?
#include <stdio.h>
void main(int argc, char *argv[], char * envp[])
{
int i;
for (i = 0; envp[i] != NULL; i++)
{
printf("\n%s", envp[i]);
}
}
So instead of what normally would be at envp[1] it is changed to "Hello World". I'm also not sure if overwrite set at 1 means envp[1].
Upvotes: 0
Views: 8540
Reputation: 582
Why do you want to modify the environment variable array? envp is just a copy of environment variables when the program starts.
First , "Hello World" is not a valid environment variable. An environment variable is just like any other variable that has an identifier(name) and a value. It is okay to have an environment variable STR=HelloWorld.
If you just want to set the above environment variable, you just call setenv("STR", "HelloWorld", 1)
. The overwrite flag 1 ensures that the previous value of STR is overwritten by this function. If the overwrite flag is 0, setenv does not change the value of the environment variable if it's already set.
Would this affect the printing of all the environments like this?
It does not change the value when I tested it with gcc. The reason is that getenv()
and setenv()
function are used in pairs to access environment variables. The c string array envp is just the environment variable array when the program starts. Also, envp is usually not passing around from main function, which means other functions are not aware of envp.
Upvotes: 2