简体   繁体   English

如何在 c 编程语言中从 $PATH 添加和删除文件名?

[英]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.我发现这个链接提供了如何在$PATH中添加文件名,但在 c 编程语言中没有。 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.有趣的是,当我输入system("echo $PATH:~/opt/bin")时,它成功显示了修改后的路径。 Also, I'm not sure how to remove the same file name ( ~/opt/bin ) from the modified path.另外,我不确定如何从修改后的路径中删除相同的文件名( ~/opt/bin )。

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.不幸的是, getenvsetenv不修改路径。 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.代码打印出硬编码的$PATH:~/opt/bin而不是通常的$PATH命令。

Thanks to @clpgr, I could write the following codes to save the result of $PATH in a char string.感谢@clpgr,我可以编写以下代码将 $PATH 的结果保存在 char 字符串中。

int main (void) {

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 C编程语言,最短路径 - C programming language, shortest path 如何将Tcpreplay添加为C语言或任何其他编程语言的库? - How to add Tcpreplay as a library in C language or any other programming language? 如何使用C编程语言在函数中添加记录(结构)? - How to add records (struct) in a function in the C programming language? 如何使用C编程语言将来自随机访问文件的记录放入数组中? - How to put records from a random access file into an array in the C programming language? 用c编程语言将数据从文件读取到结构中 - Reading data from file into structure in c programming language 我将如何使用 c 语言将文件名的路径传递给 void *buffer? - how will i pass the path of a file name to void *buffer using c language? 来自“Dennis Ritchie 的 C 编程语言”的程序中的“++argv”如何正确? - How is "++argv" correct in this program from "The C programming Language by Dennis Ritchie"? 来自 c 编程语言的 qsort function 如何工作 - how qsort function from the c programming language works 数组与 C 编程语言中的结构和联合有何不同? - How Array is different from Structures and Unions in C programming Language? “ C编程语言”中的代码如何工作? - how does this code from “The C Programming Language” work?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM