10 using error::throwTrace;
15 m_defaults(keyAndDefaults),
26 std::regex re(R
"(\s*(\S+?)\s*=\s*(\S*)\s*)"); 29 FILE *tmpfp = nullptr;
30 if (::_wfopen_s(&tmpfp, m_fileName, L
"r") != 0) {
32 if (::_wfopen_s(&tmpfp, m_fileName, L
"r") != 0) {
33 throwTrace<FrameworkError>(
"Load config file failed");
39 while (::fgets(line,
LineCharMax, fp.get()) !=
nullptr) {
40 size_t len = ::strlen(line);
41 if (line[len - 1] ==
'\n') {
43 if (std::regex_match(line, match, re)) {
44 const std::string key = match.str(1);
45 const std::string value = match.str(2);
54 while (::fgets(line,
LineCharMax, fp.get()) !=
nullptr) {
56 size_t len = ::strlen(line);
57 if (line[len - 1] ==
'\n') {
70 FILE *tmpfp =
nullptr;
71 if (::_wfopen_s(&tmpfp, m_fileName, L
"w") != 0) {
72 throwTrace<FrameworkError>(
"Save config file failed");
76 for (
const auto &pair : m_defaults) {
77 const std::string &key = pair.first;
78 const std::string &value =
getString(key);
79 ::fprintf_s(fp.get(),
"%s=%s\n", key.c_str(), value.c_str());
85 if (m_defaults.find(key) == m_defaults.end()) {
86 throwTrace<std::invalid_argument>(
"Key not found: " + key);
93 auto res = m_map.find(key);
94 if (res == m_map.end()) {
95 res = m_defaults.find(key);
96 if (res == m_defaults.end()) {
97 throwTrace<std::invalid_argument>(
"Key not found: " + key);
106 const std::string &value =
getString(key);
116 const std::string &value =
getString(key);
124 throwTrace<std::logic_error>(
"Invalid default bool: " + value);
133 const std::string &value =
getString(key);
136 int ivalue = std::stoi(value, &idx, 0);
137 if (idx != value.size())
138 throwTrace<std::invalid_argument>(value);
141 catch (
const std::logic_error &) {
147 const std::string &value =
getString(key);
150 int ivalue = std::stoi(value, &idx, 0);
151 if (idx != value.size()) {
152 throwTrace<std::invalid_argument>(value);
156 catch (
const std::logic_error &) {
157 throwTrace<std::logic_error>(
"Invalid default int: " + value);
const char *const BoolStrTrue
const char *const BoolStrFalse
std::unique_ptr< FILE, FileDeleter > FilePtr
unique_ptr of FILE with FileDeleter.
void writef(const wchar_t *fmt,...) noexcept
Write debug message using format string like printf.
int getInt(const std::string &key)
void setString(const std::string &key, const std::string &value)
void writeLine(const wchar_t *str=L"") noexcept
Write debug string and new line.
const std::string & getString(const std::string &key) const
ConfigFile(const wchar_t *fileName, InitList keyAndDefaults)
bool getBool(const std::string &key)
std::unique_ptr< wchar_t[]> utf82wc(const char *in)
UTF-8 to wide char.
static const size_t LineCharMax
std::initializer_list< MapType::value_type > InitList