在 C++ 中设置本地环境变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/899517/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 17:51:04  来源:igfitidea点击:

Set local environment variables in C++

c++cmanpage

提问by Jesse Vogt

How do I set an environment variable in C++?

如何在 C++ 中设置环境变量?

  • They do not need to persist past program execution
  • They only need to be visible in the current process
  • Preference for platform independent but for my problem only needs to work on Win32/64
  • 他们不需要坚持过去的程序执行
  • 它们只需要在当前进程中可见
  • 偏好独立于平台但我的问题只需要在 Win32/64 上工作

Thanks

谢谢

回答by alamar

NAME

       putenv - change or add an environment variable

SYNOPSIS

       #include <stdlib.h>

       int putenv(char *string);

DESCRIPTION
       The  putenv()  function adds or changes the value of environment
       variables.  The argument string is of the form name=value.  If name does
       not already exist in the environment, then string is added  to  the
       environment.   If name does exist, then the value of name in the
       environment is changed to value.  The string pointed to by string becomes
       part of the environment, so altering the string changes the environment.

On Win32 it's called _putenv I believe.

在 Win32 上,我相信它被称为 _putenv。

See SetEnvironmentVariablealso if you're a fan of long and ugly function names.

如果您喜欢又长又丑的函数名,请参阅SetEnvironmentVariable

回答by JohnMcG

I'm not positive environment variables are what you need, since they aren't going to be used outside of this run of the program. No need to engage the OS.

我不是肯定的环境变量是你所需要的,因为它们不会在程序运行之外使用。无需使用操作系统。

You might be better off having a singleton class or a namespace that holds all these values, and initialize them when you start the program.

您最好拥有一个单例类或一个包含所有这些值的命名空间,并在启动程序时对其进行初始化。

回答by jayant panhalkar

#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<string.h>
    main(int argc,char *argv[])
    {

    char *var,*value;
        if(argc==1||argc>3)
        {
        fprintf(stderr,"usage:environ variables \n");
        exit(0);
        }
    var=argv[1];
    value=getenv(var);
    //---------------------------------------
        if(value)
        {
        printf("variable %s has value %s \n",var,value);
        }
        else 
        printf("variable %s has no value \n",var);  
        //----------------------------------------
        if(argc==3)
        {
        char *string;
        value=argv[2];
        string=malloc(strlen(var)+strlen(value)+2);
            if(!string)
            {
            fprintf(stderr,"out of memory \n");
            exit(1);
            }   
            strcpy(string,var);
            strcat(string,"=");
            strcat(string,value);
            printf("calling putenv with: %s \n",string);
            if(putenv(string)!=0)
            {
            fprintf(stderr,"putenv failed\n");
            free(string);
            exit(1);
            }
                        value=getenv(var);
            if(value)
                 printf("New value of %s is %s \n",var,value);
            else
            printf("New value of %s is null??\n",var);
        }     
        exit(0);

    }//----main





/* commands to execure on linux   compile:- $gcc -o  myfile myfile.c
                      run:- $./myfile xyz
                                            $./myfile abc
                                            $./myfile pqr
*/

回答by MarkR

There's also setenv, which is slightly more flexible than putenv, in that setenvchecks to see whether the environment variable is already set and won't overwrite it, if you set the "overwrite" argument indicating that you don't want to overwrite it, and also in that the name and value are separate arguments to setenv:

还有一个setenv比 稍微灵活的方法putenv,它会setenv检查环境变量是否已经设置并且不会覆盖它,如果你设置了“overwrite”参数表明你不想覆盖它,并且因为名称和值是单独的参数setenv

NAME
        setenv - change or add an environment variable
SYNOPSIS
       #include <stdlib.h>

       int setenv(const char *name, const char *value, int overwrite);

       int unsetenv(const char *name);

   Feature Test Macro Requirements for glibc (see feature_test_macros(7)):

       setenv(), unsetenv():
           _POSIX_C_SOURCE >= 200112L
               || /* Glibc versions <= 2.19: */ _BSD_SOURCE
DESCRIPTION
       The setenv() function adds the variable name to the environment with
       the value value, if name does not already exist.  If name does exist
       in the environment, then its value is changed to value if overwrite
       is nonzero; if overwrite is zero, then the value of name is not
       changed (and setenv() returns a success status).  This function makes
       copies of the strings pointed to by name and value (by contrast with
       putenv(3)).

       The unsetenv() function deletes the variable name from the
       environment.  If name does not exist in the environment, then the
       function succeeds, and the environment is unchanged.

I'm not saying either is better or worse than the other; it just depends on your application.

我并不是说其中一个比另一个更好或更差;这仅取决于您的应用程序。

See http://man7.org/linux/man-pages/man3/setenv.3.html

http://man7.org/linux/man-pages/man3/setenv.3.html