-
Notifications
You must be signed in to change notification settings - Fork 1
/
config.cpp
84 lines (75 loc) · 2.33 KB
/
config.cpp
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
78
79
80
81
82
83
84
#include "config.h"
/*
* config::config():
* Creates _config_folder_path and _config_file_path if not present and initializes file default_values.
* If file is already present the initialization part is skipped. _config_values is then populated
*/
config::config(const std::string &config_folder_path,const std::string &file_name,
const std::map<std::string, std::string> &default_values){
_config_folder_path = config_folder_path;
//If folder does not exist create it
if(!IsPathExist(_config_folder_path)){
std::string command = "mkdir ";
command += _config_folder_path;
system(command.c_str());
}
_config_file_path = config_folder_path + "/" + file_name;
//If file does not exist create and initialize it
if(fexists(_config_file_path)){
_populate_config_values();
}
else{
_init_config_file(default_values);
_populate_config_values();
}
}
/*
* config::_init_config_file()
*/
void config::_init_config_file(const std::map<std::string, std::string> &default_values) {
config_values = default_values;
write_config_file();
}
/*
* config::_populate_config_values():
* reads configuration file pointed by _config_file_path and populates config_values map
*/
void config::_populate_config_values() {
std::ifstream configfile(_config_file_path.c_str());
while(configfile){
std::string line, field, val;
int i = 1;
getline(configfile, line);
//store field name in field
while(i < line.size() && line[i] != '*'){
field += line[i];
++i;
}
while(line[++i] != '*');
++i;
//store value in value
while(i < line.size() && line[i] != '*'){
val += line[i];
++i;
}
config_values[field] = val;
}
configfile.close();
}
/*
* config::write_config_file():
* deletes the saved configuration file and replaces it with values in config_values
*/
void config::write_config_file() const{
std::ofstream configfile(_config_file_path, std::ios::trunc);
for(auto &val: config_values){
configfile << "*" << val.first << "* = *" << val.second << "*" << std::endl;
}
configfile.close();
}
/*
* config::get_folder_path():
*/
std::string config::get_folder_path() const{
return _config_folder_path;
}