programing

C++에서 로컬 환경 변수 설정

prostudy 2022. 7. 26. 22:14
반응형

C++에서 로컬 환경 변수 설정

C++에서 환경변수를 설정하려면 어떻게 해야 합니까?

  • 과거의 프로그램 실행을 유지할 필요는 없습니다.
  • 현재 프로세스에서만 표시되어야 합니다.
  • 플랫폼에 의존하지 않고 Windows 32/64에서만 문제 발생 가능

고마워요.

이름.
putenv - 환경변수를 변경 또는 추가합니다.
개요
#ltstdlib &ltstlib.h>
int putenv(char *string);

묘사putenv() 함수는 환경의 값을 추가하거나 변경합니다.변수입니다.인수 문자열은 name=value 형식입니다.이름이 해당될 경우환경에 아직 존재하지 않는 경우 문자열이 에 추가됩니다.환경.이름이 존재하는 경우 이름 값은환경을 가치로 변경합니다.문자열이 가리키는 문자열은환경의 일부이므로 문자열을 변경하면 환경이 변경됩니다.

Win32에서는 _putenv라고 합니다.

길고 못생긴 함수 이름을 좋아하는 경우 SetEnvironmentVariable을 참조하십시오.

그리고 또setenv이것은, 보다 약간 더 유연합니다.putenv, 그 안에서setenv환경변수가 이미 설정되어 있고 덮어쓰지 않는지, 덮어쓰지 않음을 나타내는 "syslog" 인수를 설정한 경우 및 이름과 값이 별도의 인수인 경우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 를 참조해 주세요.

이 프로그램 실행 이외에는 사용하지 않을 것이기 때문에 환경변수가 필요한 것은 아닙니다.OS를 사용할 필요가 없습니다.

이러한 값을 모두 포함하는 싱글톤 클래스나 네임스페이스가 있으면 프로그램을 시작할 때 초기화하는 것이 좋습니다.

#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

언급URL : https://stackoverflow.com/questions/899517/set-local-environment-variables-in-c

반응형