0

How do I use C/C++ to set the environment variant?
I used

putenv()

but after I ran the code,the environment variant didn't change anything.

Code:

#include <stdlib.h>
#include <iostream>
#include <string.h>
using namespace std;
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 tried the function "setenv()" before but the error message:

error: 'setenv' was not declared in this scope

My OS is Windows 7.

IDE Code::block

Grzegorz Adam Kowalski
  • 5,243
  • 3
  • 29
  • 40
Ken
  • 13
  • 1
  • 4

2 Answers2

3

I tried the function "setenv()" before but the error message:

error: 'setenv' was not declared in this scope

The setenv function is declared in the stdlib.h header. You need to include this header in order to call the function:

#include <stdlib.h>

If you absolutely must use one of these functions, I would recommend using setenv in preference to putenv. Jonathan Leffler discusses the rationale in more detail here.

I would personally prefer to call the Win32 SetEnvironmentVariable function, considering that both setenv and putenv are non-portable anyway.

But I'm not really sure why you think you need to modify the environment in the first place. The question doesn't explain what problem you're trying to solve, nor does it say what were you expecting to change.

Remember that both of these functions only change the environment for the calling process. They do not have any effect on the global system environment.

For testing purposes, you will need to set the environment variable of your choice, and then use something like getenv or GetEnvironmentVariable to retrieve and print the current environment variables for the process to make sure that yours got set properly.

Community
  • 1
  • 1
Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
  • i have to include the library but i really don't know why setenv get that error message and why putenv didn't change anything – Ken Jul 10 '13 at 15:13
  • and i really don't like to use windows.h.it makes my program run slow – Ken Jul 10 '13 at 15:32
  • There is no way that including a header could make your program slow. Only the declarations you actually use are linked into your app. And even then, all of the Windows functions are in DLLs, so little more than a single instruction gets compiled into your code. Certainly no more so than the functions in stdlib.h. If you mean that it slows down compiles, you should look into using pre-compiled headers. System header files like Windows.h are a perfect place to benefit from pre-compiled headers. – Cody Gray - on strike Jul 10 '13 at 18:40
1

putenv() only affects current process. It's natural that the environment variables remain unchanged if you check them AFTER running the code.

Manas
  • 598
  • 3
  • 14