-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdotenv.h
More file actions
73 lines (69 loc) · 2.2 KB
/
Copy pathdotenv.h
File metadata and controls
73 lines (69 loc) · 2.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/*
* ☕️ Buy me a coffee ☕️ BTC: bc1qa9h0mq5ydph66ju3p9a5vpmjm6wezzaqayeasc
*
* Lightweight and high-performance .env loader for C++.
*
* Features:
* - Extremely fast: can load ~10,000 lines in under 0.25 seconds.
* - Simple and self-contained: single header, no dependencies.
* - Inspired by Python's load_dotenv() and other minimal .env libraries.
*
* Usage:
* Call `LoadDotenv("/path/to/.env")` to load environment variables into your program.
*
* Example:
* LoadDotenv("config/.env");
* const char* dbUser = std::getenv("DB_USER");
*
* Notes:
* - Supports standard key=value format.
* - Designed for maximum speed and minimal overhead.
*/
#ifndef DOTENV_H
#define DOTENV_H
#include <iostream>
#include <vector>
#include <string>
#include <cstdlib>
#include <fstream>
#include <algorithm>
#include <ranges>
inline void load_dotenv(std::string FilePath = ".env") {
std::ifstream File(FilePath);
if (!File.is_open()) {
std::cerr << "ERROR: Could not find file." << '\n';
return;
}
std::string Line;
std::vector<std::string> DataArray;
while (std::getline(File, Line)) {
Line.erase(std::remove(Line.begin(), Line.end(), ' '), Line.end());
size_t Pos = Line.find('#');
if (Pos != std::string::npos) {
Line = Line.substr(0, Pos);
}
if (Line.empty()) {
continue;
}
DataArray.clear();
for (auto&& part : Line | std::views::split('=')) {
DataArray.push_back(std::string(part.begin(), part.end()));
}
if (DataArray.size() < 2) {
continue;
}
#if defined(_WIN32) || defined(_WIN64)
_putenv_s(DataArray[0].c_str(), DataArray[1].c_str());
#elif defined(__linux__)
setenv(DataArray[0].c_str(), DataArray[1].c_str(), 1);
#elif defined(__APPLE__) || defined(__MACH__)
setenv(DataArray[0].c_str(), DataArray[1].c_str(), 1);
#else
std::cerr << "ERROR: Unkown OS." << '\n';
File.close();
return;
#endif
}
File.close();
}
#endif // DOTENV_H