-
Notifications
You must be signed in to change notification settings - Fork 0
/
IniFile.hpp
77 lines (66 loc) · 1.81 KB
/
IniFile.hpp
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
74
75
76
77
#pragma once
#include <unordered_map>
#include <string>
#include <fstream>
#include <exception>
#include <regex>
class IniFile
{
std::string filePath;
std::unordered_map<std::string, std::string> container;
std::ifstream iFile;
public:
IniFile(const char * _filePath) : filePath(_filePath)
{
// ^([A-Z|a-z][^\s]*)\s*=\s*(.*)$
std::string rawRegex("^([A-Z|a-z][^\\s]*)\\s*=\\s*(.*)$");
std::regex regex(rawRegex);
iFile.open(filePath);
if (!iFile.is_open())
throw std::invalid_argument("Can't open file at given location");
int lineNumber = 0;
while (!iFile.eof())
{
std::string line;
std::smatch matches;
std::getline(iFile, line);
lineNumber++;
if (std::regex_match(line, matches, regex))
{
if (container.find(matches[1].str()) != container.end())
throw std::logic_error("Value " + matches[1].str() + " already exists!");
container[matches[1].str()] = matches[2].str();
}
else if (line[0] != '#')
{
std::cerr << "[IniFile] Cannot parse " << lineNumber << " line in file " << filePath << "\n";
}
}
iFile.close();
}
std::string getRaw(std::string key)
{
if (container.find(key) == container.end())
throw std::logic_error("Value " + key + " not found!");
return container[key];
}
std::string getString(std::string key)
{
return getRaw(key);
}
bool getBool(std::string key)
{
if (container.find(key) == container.end())
throw std::logic_error("Value " + key + " not found!");
std::string value(container[key]);
if (std::regex_search(value, std::regex("^((true)|(1))$", std::regex::icase)))
return true;
if (std::regex_search(value, std::regex("^((false)|(-1)|(0))$", std::regex::icase)))
return false;
throw std::logic_error(key + " is not boolean");
}
int getInt(std::string key)
{
return std::stoi(container[key]);
}
};