Well, this morning I tried to write a program to update environment variable's list. And I got stuck at a very crucial point. I think am making some silly mistake. A second opinion will be helpful.

1) Take complete path of environment variable into a string variable 'env'.
2) Concatenate it with string 'set path=' + env + ';%path%'
3) Pass this string to system().
4) Check if system() is executed correctly.



int main(){
    char env[200];
    printf("Path of env variable: ");
    strcpy(env,strcat(strcat("\"set path=",env),"%path%;\"")); // <-- Point of mistake.
     if ( system(env) != -1){                                 // <-- Point of mistake.
        puts("Environment Variable set.");
        puts("Failed to set environment variable.");
    return 0;

Thanks :-)

2 Years
Discussion Span
Last Post by N1GHTS

The environment variable is set for only the current process, it does not affect system-wide global environment variables. You can simulate the same problem by doing the same in a command window, close the window, open another window and inspecting the environment variable you tried to set the first time. You will discover that the environment variable reverts to whatever it was before you tried to change it.


@Ancient Dragon: Yea, you are dead on. So how do I change global environment variable via a C program ?

I know how to set it manually using GUI. But I want to do this program as a part of exercise.



Setting global environment variables are OS specific, and are essentially managed by the OS itself. The OS is responsible for passing on the default environment values to new process spaces.

Therefore you will want to refer to your Operating system's requirements.

In Windows it is stored in the system registry. To access it from the command line you can use SETX or if you are including <windows.h> use the Windows API to access HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment or HKEY_CURRENT_USER\Environment.

In Linux it can be distribution specific, but at least in Ubuntu the environment is configured in the ~/.profile file.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.