EDIT
Unfortunately, getenv
or setenv
do not modify the path. When I used the following code
int main() {
char *oldenv = strdup(getenv("PATH")); // Make a copy of your PATH
setenv("PATH", "$PATH:~/opt/bin", 1); // Overwrite it
system("echo $PATH"); // Outputs "$PATH:~/opt/bin"
setenv("PATH", oldenv, 1); // Restore old PATH
free(oldenv); // Don't forget to free!
system("echo $PATH"); // Outputs your actual PATH
}
the codes prints out the hard-coded $PATH:~/opt/bin
instead of the usual $PATH
command.
End of Edit
I found that this link provides how to add the file name in $PATH
but not in c programming language. When I run the codes, it simply prints out the original path instead of the modified path. Interestingly, when I put system("echo $PATH:~/opt/bin")
, it successfully show the modified path. Also, I'm not sure how to remove the same file name (~/opt/bin
) from the modified path.
My codes are here:
int main (void) {
system("echo $PATH");
system("export PATH=$PATH:~/opt/bin");
system("echo $PATH"); //prints out the original $PATH
}