forked from danielshaving/redis-cpp17
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathxIni.h
107 lines (91 loc) · 2.05 KB
/
xIni.h
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
#pragma once
#include "all.h"
#include "xLog.h"
typedef std::map<std::string, std::string> INI_DATA_MAP;
class xINIParser
{
private:
INI_DATA_MAP map;
public:
xINIParser(const char *file, const char *title)
{
getDataFromFile(file, title);
}
~xINIParser() { map.clear(); }
std::string getStringData(const char* key)
{
auto iter = map.find(key);
if (iter != map.end())
{
return iter->second;
}
std::string str;
return str;
}
int getNumberData(const char* key)
{
auto iter = map.find(key);
if (iter != map.end())
{
return atoi(iter->second.c_str());
}
return 0;
}
INI_DATA_MAP getMap() { return map; }
private:
void getDataFromFile(const char* file, const char *title)
{
char *value, sect[30], c;
char linebuf[1024];
FILE *inifp;
strcpy(sect, "[");
strcat(sect, title);
strcat(sect, "]");
if ((inifp = fopen(file, "rb")) == nullptr)
{
LOG_WARN<<"read file error";
return;
}
while ((c = fgetc(inifp)) != EOF)
{
if (c == '[' && c != '#')
{
ungetc(c, inifp);
fgets(linebuf, 1024, inifp);
if (strstr(linebuf, sect))
{
while ((c = fgetc(inifp)) != '[' && c != EOF)
{
ungetc(c, inifp);
fgets(linebuf, 1024, inifp);
if (linebuf[0] == '#') continue;
char strKey[64] = "", strValue[512] = "";
char *ptr;
char *p;
ptr = strtok_r(linebuf, "=\n\r ", &p);
bool bValid = false;
if (ptr != nullptr)
{
strcpy(strKey, ptr);
ptr = strtok_r(nullptr, "=\n\r ", &p);
if (ptr != nullptr)
{
strcpy(strValue, ptr);
bValid = true;
}
}
if (bValid) map.insert(INI_DATA_MAP::value_type(strKey, strValue));
}
if (c==EOF) continue;
ungetc(c, inifp);
}
}
else
{
ungetc(c, inifp);
fgets(linebuf, 1024, inifp);
}
}
fclose(inifp);
}
};