Member Avatar for Rahul47

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.

Algorithm:
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.

Code:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

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

Thanks :-)

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.

Member Avatar for Rahul47

@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.

Thanx.

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.