diff --git a/src/string_utils.cpp b/src/string_utils.cpp index 78cfc3c..1bfe8a4 100644 --- a/src/string_utils.cpp +++ b/src/string_utils.cpp @@ -76,19 +76,27 @@ string sc::file_get_contents(const string& path) return {buf.data(), static_cast(file_len)}; } -map sc::parse_ini_file(const string& path) +map sc::parse_ini_file(const string& path, bool ignore_sections) { map result; + string prefix; string line; ifstream file {path}; - file.exceptions(/*ios::failbit |*/ ios::badbit); // it seems that getline() will set failbit when confronted with eof immediately + file.exceptions(ios::badbit); // it seems that getline() will set failbit when confronted with eof immediately while (getline(file, line)) { - if (line[0] == '[') continue; - vector parts {split(line, "=")}; - if (parts.size() > 1) { - string key {trim(parts[0])}; - string value {trim(parts[1], " \"")}; - result[key] = value; + if (line[0] == '#') continue; // ignore comments + if (line[0] == '[') { + if (ignore_sections) continue; + regex section {R"(^\[(.*)\])"}; + smatch m; + if (regex_search(line, m, section)) { + prefix = string{m[1]} + '.'; + } + } + regex key_value_pat {R"(^\s*(.*)\s*=\s*("?)(.*)\2)"}; + smatch match; + if (regex_search(line, match, key_value_pat)) { + result[prefix + string{match[1]}] = match[3]; } } return result; diff --git a/src/string_utils.hpp b/src/string_utils.hpp index 34059f8..df835de 100644 --- a/src/string_utils.hpp +++ b/src/string_utils.hpp @@ -44,7 +44,7 @@ namespace sc { std::string file_get_contents (const std::string& path); - std::map parse_ini_file (const std::string& path); + std::map parse_ini_file (const std::string& path, bool ignore_sections = true); void create_dir (const std::string& path, int mode = 0777);