#include #include #include #include #include #include #include #include #include #include #include #include std::vector split(std::string s, std::string delimiters) { std::vector tokens; size_t last = 0, next = 0; while ((next = s.find_first_of(delimiters, last)) != std::string::npos) { if (next != last) tokens.push_back(s.substr(last, next - last)); last = next + 1; } if (last < s.length()) tokens.push_back(s.substr(last)); return tokens; } std::string trim(std::string& source) { auto line = source; std::string whitespaces(" \t\n\r\f\v"); line.erase(0, line.find_first_not_of(whitespaces)); line.erase(line.find_last_not_of(whitespaces) + 1); return line; } std::expected str2int (std::string source) { std::size_t pos{}; int res; try { res = std::stoi(source, &pos); } catch (std::invalid_argument const& ex) { return std::unexpected(std::format("invalid argument:{}", ex.what())); } catch (std::out_of_range const& ex) { return std::unexpected(std::format("out of range", ex.what())); } return res; } class Registry { private: std::map kvmap; std::vector localnets; std::string tunnelnet; int listenport; public: std::expected Read(std::string filename); int Listenport(void); std::string Tunnelnet(void); std::vector Localnets(void); }; int Registry::Listenport(void){ return listenport; } std::vector Registry::Localnets(void){ return localnets; } std::string Registry::Tunnelnet(void){ return tunnelnet; } std::expected Registry::Read(std::string filename) { std::ifstream file; file.open(filename); if (file.fail()) { auto state = file.rdstate(); if (state & std::ios_base::badbit) { return std::unexpected("Read/writing error on i/o operation"); } else if (state & std::ios_base::failbit) { return std::unexpected("Logical error on i/o operation"); } } std::string line; while (std::getline(file, line)) { auto tokens = split(line, "#;"); auto keyval = trim(tokens[0]); if (keyval.size() == 0) continue; tokens = split(keyval, "="); if (tokens.size() < 2) continue; auto key = trim(tokens[0]); auto val = trim(tokens[1]); kvmap[key] = val; if (key == "localnet") { localnets.push_back(val); } else if (key == "tunnelnet") { tunnelnet = val; } else if (key == "listenport") { auto convRes = str2int(val); if (!convRes) { auto msg = std::format("listenport: {}", convRes.error()); return std::unexpected(msg); } listenport = convRes.value(); } } file.close(); //for (auto const& [key, val] : kvmap) { // std::cout << key << ":" << val << std::endl; //} return {}; } int main() { Registry config; auto openRes = config.Read("example.conf"); if (!openRes) { std::cerr << openRes.error() << std::endl; return 1; } return 0; }