-
Notifications
You must be signed in to change notification settings - Fork 2
/
ParametersMap.cpp
116 lines (92 loc) · 2.53 KB
/
ParametersMap.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
115
#include "ParametersMap.h"
template<typename T>
std::string
toString(const std::string &fmt, T val)
{
char buffer[256];
sprintf(buffer, fmt.c_str(), val);
return std::string(buffer);
}
void ParametersMap::save(const std::string &fname) const
{
FILE *f = fopen(fname.c_str(), "w");
if(f == NULL) {
throw std::runtime_error("Could not open file " + fname + " for writing");
}
save(f);
fclose(f);
}
void ParametersMap::save(FILE *f) const
{
fprintf(f, "%lu\n", size());
for(ParametersMap::const_iterator i = begin(); i != end(); i++) {
fprintf(f, "%s %s\n", i->first.c_str(), i->second.c_str());
}
}
void ParametersMap::load(FILE *f)
{
int n;
fscanf(f, "%d", &n);
for(int i = 0; i < n; i++) {
char key[256], val[256];
fscanf(f, "%s %s\n", key, val);
(*this)[key] = val;
}
}
void ParametersMap::set(const std::string &key, double val)
{
// TODO: throw exception if key has a space in it
(*this)[key] = toString("%f", val);
}
void ParametersMap::set(const std::string &key, int val)
{
(*this)[key] = toString("%d", val);
}
void ParametersMap::set(const std::string &key, const std::string &val)
{
(*this)[key] = val;
}
int ParametersMap::getInt(const std::string &key) const
{
return atoi(this->at(key).c_str());
}
double ParametersMap::getFloat(const std::string &key) const
{
return atof(this->at(key).c_str());
}
const std::string & ParametersMap::getStr(const std::string &key) const
{
return this->at(key);
}
void saveToFile(const std::string &fname, const std::map<std::string, ParametersMap> ¶ms)
{
using namespace std;
FILE *f = fopen(fname.c_str(), "w");
if(f == NULL) {
throw std::runtime_error("Could not open file " + fname + " for writing");
}
fprintf(f, "%d\n", (int)params.size());
for(map<string, ParametersMap>::const_iterator i = params.begin(); i != params.end(); i++) {
fprintf(f, "%s\n", i->first.c_str());
i->second.save(f);
}
fclose(f);
}
void loadFromFile(const std::string &fname, std::map<std::string, ParametersMap> ¶ms)
{
using namespace std;
FILE *f = fopen(fname.c_str(), "r");
if(f == NULL) {
throw std::runtime_error("Could not open file " + fname + " for reading");
}
int nParamMaps = 0;
fscanf(f, "%d", &nParamMaps);
for(int i = 0; i < nParamMaps; i++) {
char key[100];
fscanf(f, "%s", key);
ParametersMap tmp;
tmp.load(f);
params[key] = tmp;
}
fclose(f);
}