summaryrefslogtreecommitdiff
path: root/common/config.cpp
blob: f10630490c1494e9e1d315ed77a42278fe757499 (plain)
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"

#include <fstream>
#include <iostream>
#include <sstream>

Config::Config() {
	path = "aotenjou.conf";
	load_conf();
}

Config::Config(std::string path) {
	path = path;
	load_conf();
}

Config::~Config() {
	save_conf();
}

/*
  Adds a config-element to the list
  */
void Config::add_element(std::string keyword, std::string value) {
    config[keyword] = value;
}

void Config::add_element(std::string keyword, int value) {
	std::stringstream out;
	out << value;
	config[keyword] = out.str();
}

/*
Load a value from the config.
  */
std::string Config::get_element(std::string keyword) {
    return config[keyword];
}

/*
  Initializes and loads the config from disk if it exists
  */
void Config::load_conf(){
		
	std::ifstream config_file(path.c_str());
	
	if(config_file.is_open()) {
		while(config_file.good()) {
			std::string config_line;
			std::getline(config_file, config_line);
			std::string id    = config_line.substr(0, config_line.find("=") - 1);
			//Skip empty lines
			if (id != "") {
				std::string value = config_line.substr(config_line.find("=") + 2, config_line.length()-1);
				config[id] = value;
			}
		}
		
		config_file.close();
		
	} else {
		std::cerr << "Unable to open configuration file..." << std::endl;
	}
}

/*
  Saves the current config to disk
  */
void Config::save_conf(){

	std::ofstream config_file(path.c_str(), std::ios::out | std::ios::trunc);
	
	if(config_file.is_open()) {
		for(std::map<std::string, std::string>::iterator it = config.begin(); it != config.end(); ++it) {
			config_file << it->first << " = " << it->second << std::endl;
		}
		
		config_file.close();
	} else {
		std::cerr << "Unable to save to configuration file..." << std::endl;
	}
}