简体   繁体   中英

How to add and remove file name from $PATH in c programming language?

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

}

Unfortunately, getenv or setenv do not modify the path. When I used the following code here ,

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.

Thanks to @clpgr, I could write the following codes to save the result of $PATH in a char string.

int main (void) {

  char* path;
  path = getenv("PATH");
  if (path)
  {
    printf(path);    
  }  
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM