[英]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.不幸的是,
getenv
或setenv
不修改路径。 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.