Server/C++

C++ 환경변수 .env 파일 사용하기

Juzdalua 2025. 1. 3. 11:10

C++에서 .env 파일을 사용하는데, getenv 함수가 deprecated 되었다.

직접 환경변수를 저장하지 않고 메모리상 map에 key-value 값으로 사용하게끔 만들었다.

간단하다. 파일을 읽어오고 "="라는 delimiter를 기준으로 key-value로 map에 저장하고 메모리에 갖고있게끔 했다.


프로젝트 root 폴더에 .env 파일을 위치시킨다.

 

// Utils.h
#pragma once
#include <cstdlib>
#include <fstream>
#include <string>

class Utils
{
public:
	Utils() = delete;

public:
	static void Init(const std::string& filePath = "../.env");
	static std::string getEnv(const std::string& key);

private:
	static map<std::string, std::string> envVariables;
};
// Utils.cpp
#include "pch.h"
#include "Utils.h"

map<std::string, std::string> Utils::envVariables;

void Utils::Init(const string& filePath)
{
	std::ifstream envFile(filePath);
	ASSERT_CRASH(envFile.is_open());

	std::string line;
	while (std::getline(envFile, line))
	{
		if (line.empty() || line[0] == '#') continue;

		size_t delimiterPos = line.find('=');
		if (delimiterPos != std::string::npos)
		{
			std::string key = line.substr(0, delimiterPos);
			std::string value = line.substr(delimiterPos + 1);
			envVariables[key] = value;
		}
	}

	envFile.close();
}

string Utils::getEnv(const string& key)
{
	auto it = envVariables.find(key);
	if (it != envVariables.end()) return it->second;
	return "";
}
// .env
TEST=test

// main.cpp
const string testMsg = Utils::getEnv("TEST");
const wstring wTestMsg = std::wstring().assign(testMsg.begin(), testMsg.end()); // convert to wstring

'Server > C++' 카테고리의 다른 글

비트연산  (0) 2025.04.17
C++ MySQL 연동 - ODBC  (0) 2024.11.21
JSON 사용하기 - nlohmann json  (1) 2024.11.20
Boost 라이브러리 사용하기  (0) 2024.11.19
C++ MySQL 연동 - Connector/C++  (0) 2024.08.30