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

发布于 2024-07-21 18:18:15 字数 136 浏览 5 评论 0原文

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

  • 它们不需要保留过去的程序执行
  • 它们只需要在当前进程中可见
  • 偏好独立于平台但对于我的问题只需要在 Win32/64 上工作

谢谢

How do I set an environment variable in 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

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

如何视而不见 2024-07-28 18:18:17

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

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

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.

和我恋爱吧 2024-07-28 18:18:17
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>

int 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
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>

int 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
姐不稀罕 2024-07-28 18:18:16

还有 setenv,它比 putenv 稍微灵活一些,因为 setenv 检查环境变量是否已经设置,并且不会设置覆盖它,如果您设置“覆盖”参数表明您不想覆盖它,并且名称和值是 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.

我并不是说两者都是比对方更好或更差; 这仅取决于您的应用程序。

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

There's also setenv, which is slightly more flexible than putenv, in that setenv checks 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:

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

窗影残 2024-07-28 18:18:15
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.

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

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

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.

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文