본문 바로가기

운동하는 개발자/c++

C++ 윈도우 환경변수 값 획득 (Get Windows Environment Variable Values)

728x90

C++에서 ofstream 사용 시 path에 윈도우 환경변수(예시 : %appdata%)가 있으면 파일 생성이 되지 않았기에 해당 값을 획득 후 생성해야 했다

std::string 내에 환경변수가 섞여있는 경우의 예제가 없어서 직접 만들었다

std::string ReplaceEnvVar(const std::string& str)
{
    std::string result = str;
    //문자열에서 환경변수 위치 찾음
    std::size_t pos = result.find('%');
    while (pos != std::string::npos)
    {
        std::size_t endpos = result.find('%', pos + 1);
        if (endpos != std::string::npos)
        {
            std::string varname = result.substr(pos + 1, endpos - pos - 1);
            char* varvalue = nullptr;
            size_t len = 0;
            if (_dupenv_s(&varvalue, &len, varname.c_str()) == 0 && varvalue != nullptr)
            {
                result.replace(pos, endpos - pos + 1, varvalue);
                free(varvalue);
            }
            pos = result.find('%', pos + 1);
        }
        else
        {
        	break;
        }
    }
    return result;
}​

728x90