forked from zrax/tworld
-
Notifications
You must be signed in to change notification settings - Fork 1
/
settings.cpp
114 lines (95 loc) · 2.2 KB
/
settings.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
/* settings.cpp: Functions for managing settings.
*
* Copyright (C) 2014-2017 by Eric Schmidt, under the GNU General Public
* License. No warranty. See COPYING for details.
*/
#include "settings.h"
#include "err.h"
#include "fileio.h"
#include <cstdlib>
#include <fstream>
#include <map>
#include <sstream>
#include <utility>
extern char *savedir;
using std::free;
using std::getline;
using std::ifstream;
using std::istringstream;
using std::map;
using std::move;
using std::ofstream;
using std::ostringstream;
using std::string;
namespace
{
map<string, string> settings;
}
char const * sfname = "settings";
void loadsettings()
{
char *fname = getpathforfileindir(savedir, sfname);
ifstream in(fname);
free(fname);
if (!in)
return;
map<string, string> newsettings;
string line;
while (getline(in, line))
{
size_t pos(line.find('='));
if (pos != string::npos)
newsettings.insert({line.substr(0, pos), line.substr(pos+1)});
}
if (!in.eof())
warn("Error reading settings file");
settings = move(newsettings);
}
void savesettings()
{
char *fname = getpathforfileindir(savedir, sfname);
ofstream out(fname);
free(fname);
if (!out)
{
warn("Could not open settings file");
return;
}
for (map<string,string>::const_iterator i(settings.begin());
i != settings.end(); ++i)
{
out << i->first << '=' << i->second << '\n';
}
if (!out)
{
warn("Could not write settings");
}
}
int getintsetting(char const * name)
{
std::map<string, string>::const_iterator loc(settings.find(name));
if (loc == settings.end())
return -1;
std::istringstream in(loc->second);
int i;
if (!(in >> i))
return -1;
return i;
}
void setintsetting(char const * name, int val)
{
std::ostringstream out;
out << val;
settings[name] = out.str();
}
char const * getstringsetting(char const * name)
{
std::map<string, string>::const_iterator loc(settings.find(name));
if (loc == settings.end())
return nullptr;
return loc->second.c_str();
}
void setstringsetting(char const * name, char const * val)
{
settings[name] = val;
}