Click here to Skip to main content
15,895,740 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
how to use C\C++ to set environment variant
i use "putenv()"
it can run but it didn't work(environment variant didn't change)

my code
C++
int main()
{
    char a[128];
    char b[256];

    char all[512];
    cin>>a;
    cin>>b;
    cout<<'\n';
    cout<<a<<'\n';
    cout<<b<<'\n';

    strcpy(all,a);
    strcat(all,"=");
    strcat(all,b);
    cout<<all<<'\n';
    cout<<putenv(all);
}


I try to used function "setenv()" before but the error message:
error: 'setenv' was not declared in this scope
My OS is Windows 7.
IDE Code::block
Posted
Comments
Sergey Alexandrovich Kryukov 10-Jul-13 0:30am    
What is "environment variant"? Do you mean "environment variable"?
—SA

putenv() changes the environment of the local process (your program). It does not affect the environment of the system.

When a program is started, the system environment is copied to local memory of the process. When using putenv(), the environment in this local memory is changed. This modified environment can be passed to other processes created by spawn(), exec(), or system() from within your program. But when your program terminates, the local copy and all modifications are lost.
 
Share this answer
 
Comments
Ken Chiayuan Chang 11-Jul-13 5:37am    
you two are all amazing
thanks you to help me solve my question
What you're doing is the correct way to do it, but it will be applicable only to the current process and possibly its child processes.
When you check the environment variable outside your program, it will show you the old value.

On Windows you can do the same using the SetEnvironmentVariable[^] API.
 
Share this answer
 
Comments
Jochen Arndt 10-Jul-13 3:11am    
+5. I forgot the API call.
H.Brydon 10-Jul-13 17:45pm    
Right, +5. You can also create/read/update/delete environment variables using their entries in the registry. You can change your own "User" vars without privs. You will need admin access etc. for system variables.
Ken Chiayuan Chang 11-Jul-13 5:37am    
you two are all amazing
thanks you to help me solve my question

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900