How to set path environment variable in linux in C language code

心不动则不痛 提交于 2019-12-12 04:54:54

问题


I want to set a path environment variable in bash by C program. So I coded using 'setenv' function, But it was not the answer to solve.

Could anybody suggest another way to solve this problem in C programming?

I thought the other solution that the program read the profile file, then modify and save, but actually when I opened this file there's no string I wanted about PATH variable.


回答1:


You can use setenv() and putenv() to set environment variables. But these will only be set for the given program. You cannot set environment variables for the shell or its parent process.




回答2:


Here an example to define the Python path.

It is created a string path and append it to the python path.

char *append_path = malloc(sizeof(char) * 1000);
append_path = "/trunk/software/hmac_sha256/:.";
printf("Append to path is:\n%s\n", append_path);           
setenv("PYTHONPATH",append_path,1);//Set PYTHONPATH TO working directory https://www.ibm.com/support/knowledgecenter/en/SSLTBW_2.1.0/com.ibm.zos.v2r1.bpxbd00/setenv.htm
char *path = Py_GetPath();
printf("Python search path is:\n%s\n", path);

This should append the string to the PYTHONPATH environment variable. For me it is working as stated before. In case the variable is replaced and not appended, then you just need to read the environment variable before, append the new string and then do the "setenv".

for example

//include string functions
#include <string.h>

....

char *current_path = malloc(sizeof(char) * 1000);
current_path = Py_GetPath();
printf("Current search path is:\n%s\n", current_path);
char *new_path = malloc(sizeof(char) * 1000);
new_path = "/trunk/software/hmac_sha256/:.";
printf("New to add path is:\n%s\n", new_path);
snprintf(current_path, sizeof(char) * 1000, "%s%s", current_path,new_path);//this concatenate both strings
setenv("PYTHONPATH",current_path,1);//Set PYTHONPATH TO working directory https://www.ibm.com/support/knowledgecenter/en/SSLTBW_2.1.0/com.ibm.zos.v2r1.bpxbd00/setenv.htm
char *path = Py_GetPath();
printf("Python search path is:\n%s\n", path);


来源:https://stackoverflow.com/questions/29260555/how-to-set-path-environment-variable-in-linux-in-c-language-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!