C++中配置文件的读取

开发环境:Ubuntu16.04 LTS。 需要的库:Eigen3。 额外的文件:inifile.h、inifile.cpp。

前言

使用配置文件是提高项目开发效率的一个重要方法。如果不使用配置文件,当我们需要不断调整程序中的参数时,就会造成每修改一次参数需要进行一次编译的情况,
而当项目代码很庞大时,编译往往会耗费大量时间。为了节约项目开发时间,提高工作效率,就需要将待调整参数存放至配置文件中。这样做,在修改时只需要修改配
置文件中的参数,而不必对整个项目进行编译。

完整程序源码

完整程序目录入下图所示:
iniTestTree

CMakeLists.txt

1
2
3
4
5
6
cmake_minimum_required(VERSION 2.8)
project(iniTest)
set (CMAKE_CXX_STANDARD 11)
include_directories( "./include/"
"/usr/include/eigen3" )
add_executable(iniTest main.cpp ./src/inifile.cpp)

说明:

  1. include_directories是指添加所需头文件的目录,一些常规文件可自行添加,本例中为添加inifile.h需要加上”./include/“,还需手动添加”/usr/include/eigen3”。

  2. add_executable是指添加需要执行的cpp文件,注意需要将不同文件夹下的源文件包含进来。

test.ini

配置文件test.ini内容如下,主要包含两个标题,每个标题下有两个标签。(标题、标签说法可能不专业)

1
2
3
4
5
6
7
8
9
[ObjectType]
# Obj0
minHSV0=0 15 10
maxHSV0=10 25 20


[Motion]
CoeffJv=1 1 1 1.5 1.5 2 3
Pos=1 2 3 4 5 6 7

main.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
#include <iostream>
#include "stdio.h"
#include "inifile.h"
#include <Eigen/Core>
#include <Eigen/Dense>

using namespace std;
using namespace inifile;
using namespace Eigen;

#define Vector7d Matrix<double, 7, 1>
#define Vector3d Matrix<double, 3, 1>

int main() {
Vector7d a;
a << 1, 1, 1, 1, 1, 1, 1;
Vector7d &coeffJv = a;
Vector3d b;
Vector3d &minHSV0 = b;
IniFile ini;
int rtn;
string file = "../test.ini";
const char* fileName = file.c_str();
if (ini.load(fileName) < 0) {
cout << "No such file!" << endl;
return -1;
}
cout << "Load file succeed!" << endl;
cout << "\na : " << a.transpose() << endl;

string str1, str2;
string title = "Motion";
string label = "CoeffJv";
str1 = ini.getStringValue(title.c_str(), label.c_str(), rtn);

title = "ObjectType";
label = "minHSV0";
str2 = ini.getStringValue(title.c_str(), label.c_str(), rtn);
if (rtn != 0)
return -1;

sscanf(str1.c_str(), "%lf %lf %lf %lf %lf %lf %lf", &coeffJv[0],
&coeffJv[1], &coeffJv[2], &coeffJv[3],
&coeffJv[4], &coeffJv[5], &coeffJv[6]);
sscanf(str2.c_str(), "%lf %lf %lf", &minHSV0[0],
&minHSV0[1], &minHSV0[2]);

cout << "\nCoeffJv : " << coeffJv.transpose() << endl;
cout << "\na: " << a.transpose() << endl;
cout << "\nminHSV0 : " << minHSV0.transpose() << endl;
cout << "\nb: " << b.transpose() << endl;

return 1;
}

说明:

1.Q:为什么要用引用?

A:用引用的目的是为了最后通过sscanf函数将配置文件中的参数写到自己的变量中,不用引用会写入失败。sscanf函数的用法目前尚不十分明确,因此这里只是
给出一种能用的方法。使用引用时必须初始化,因此首先定义了a、b两个变量,引用只是这两个变量的两个别名,修改引用的值会改掉a、b的值。

2.Q:c_str()的作用是啥?

A:c_str()是string类下的一个函数,返回类型是const char*,这个类型在load()、getStringValue()类型中都需要用到。而直接用const char*来定义,将会
导致字符串无法修改。

3.Q:transpose()的作用为何?

A:这是matrix中的一个函数,将矩阵进行转置。

../include/inifile.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
108
109
110
111
112
113
114
115
116
117
118
#ifndef _INIFILE_H
#define _INIFILE_H

#include <map>
#include <vector>
#include <string>
#include <string.h>

using namespace std;
namespace inifile
{
const int RET_OK = 0;
const int RET_ERR = -1;
const string delim = "\n";
struct IniItem {
string key;
string value;
string comment;
};
struct IniSection {
typedef vector<IniItem>::iterator iterator;
iterator begin() {
return items.begin();
}
iterator end() {
return items.end();
}

string name;
string comment;
vector<IniItem> items;
};

class IniFile
{
public:
IniFile();
~IniFile() {
release();
}

public:
typedef map<string, IniSection *>::iterator iterator;

iterator begin() {
return sections_.begin();
}
iterator end() {
return sections_.end();
}
public:
/* 打开并解析一个名为fname的INI文件 */
int load(const string &fname);
/*将内容保存到当前文件*/
int save();
/*将内容另存到一个名为fname的文件*/
int saveas(const string &fname);

/*获取section段第一个键为key的值,并返回其string型的值*/
string getStringValue(const string &section, const string &key, int &ret);
/*获取section段第一个键为key的值,并返回其int型的值*/
int getIntValue(const string &section, const string &key, int &ret);
/*获取section段第一个键为key的值,并返回其double型的值*/
double getDoubleValue(const string &section, const string &key, int &ret);

/*获取section段第一个键为key的值,并将值赋到value中*/
int getValue(const string &section, const string &key, string &value);
/*获取section段第一个键为key的值,并将值赋到value中,将注释赋到comment中*/
int getValue(const string &section, const string &key, string &value, string &comment);

/*获取section段所有键为key的值,并将值赋到values的vector中*/
int getValues(const string &section, const string &key, vector<string> &values);
/*获取section段所有键为key的值,并将值赋到values的vector中,,将注释赋到comments的vector中*/
int getValues(const string &section, const string &key, vector<string> &value, vector<string> &comments);

bool hasSection(const string &section) ;
bool hasKey(const string &section, const string &key) ;

/* 获取section段的注释 */
int getSectionComment(const string &section, string &comment);
/* 设置section段的注释 */
int setSectionComment(const string &section, const string &comment);
/*获取注释标记符列表*/
void getCommentFlags(vector<string> &flags);
/*设置注释标记符列表*/
void setCommentFlags(const vector<string> &flags);

/*同时设置值和注释*/
int setValue(const string &section, const string &key, const string &value, const string &comment = "");
/*删除段*/
void deleteSection(const string &section);
/*删除特定段的特定参数*/
void deleteKey(const string &section, const string &key);
public:
/*去掉str后面的c字符*/
static void trimleft(string &str, char c = ' ');
/*去掉str前面的c字符*/
static void trimright(string &str, char c = ' ');
/*去掉str前面和后面的空格符,Tab符等空白符*/
static void trim(string &str);
/*将字符串str按分割符delim分割成多个子串*/
private:
IniSection *getSection(const string &section = "");
void release();
int getline(string &str, FILE *fp);
bool isComment(const string &str);
bool parse(const string &content, string &key, string &value, char c = '=');
//for dubug
void print();

private:
map<string, IniSection *> sections_;
string fname_;
vector<string> flags_;
};
}

#endif

../src/inifile.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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
#ifndef _INIFILE_CPP
#define _INIFILE_CPP
#include "inifile.h"
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>

namespace inifile {
int INI_BUF_SIZE = 2048;

IniFile::IniFile() {
flags_.push_back("#");
flags_.push_back(";");
}
bool IniFile::parse(const string &content, string &key, string &value, char c/*= '='*/)
{
int i = 0;
int len = content.length();
while (i < len && content[i] != c) {
++i;
}
if (i >= 0 && i < len) {
key = string(content.c_str(), i);
value = string(content.c_str() + i + 1, len - i - 1);
trim(key);
trim(value);
return true;
}
return false;
}

int IniFile::getline(string &str, FILE *fp)
{
int plen = 0;
int buf_size = INI_BUF_SIZE * sizeof(char);

char *buf = (char *) malloc(buf_size);
char *pbuf = NULL;
char *p = buf;

if (buf == NULL) {
fprintf(stderr, "no enough memory!exit!\n");
exit(-1);
}

memset(buf, 0, buf_size);
int total_size = buf_size;

while (fgets(p, buf_size, fp) != NULL) {
plen = strlen(p);

if (plen > 0 && p[plen - 1] != '\n' && !feof(fp)) {

total_size = strlen(buf) + buf_size;
pbuf = (char *)realloc(buf, total_size);

if (pbuf == NULL) {
free(buf);
fprintf(stderr, "no enough memory!exit!\n");
exit(-1);
}

buf = pbuf;

p = buf + strlen(buf);

continue;
} else {
break;
}
}
str = buf;
free(buf);
buf = NULL;
return str.length();

}

int IniFile::load(const string &filename)
{
release();
fname_ = filename;
IniSection *section = NULL;
FILE *fp = fopen(filename.c_str(), "r");

if (fp == NULL) {
return -1;
}

string line;
string comment;

//增加默认段section = new IniSection();
sections_[""] = section;

while (getline(line, fp) > 0) {

trimright(line, '\n');
trimright(line, '\r');
trim(line);

if (!isComment(line)) {
string subline;
string tmp = line;

for (size_t i = 0; i < flags_.size(); ++i) {
subline = line.substr(0, line.find(flags_[i]));
line = subline;
}

comment += tmp.substr(line.length());
}

trim(line);

if (line.length() <= 0) {
continue;
}

if (line[0] == '[') {
section = NULL;
int index = line.find_first_of(']');

if (index == -1) {
fclose(fp);
fprintf(stderr, "没有找到匹配的]\n");
return -1;
}

int len = index - 1;

if (len <= 0) {
fprintf(stderr, "段为空\n");
continue;
}

string s(line, 1, len);

if (getSection(s.c_str()) != NULL) {
fclose(fp);
fprintf(stderr, "此段已存在:%s\n", s.c_str());
return -1;
}

section = new IniSection();
sections_[s] = section;

section->name = s;
section->comment = comment;
comment = "";
} else if (isComment(line)) {
if (comment != "") {
comment += delim + line;
} else {
comment = line;
}
} else {
string key, value;

if (parse(line, key, value)) {
IniItem item;
item.key = key;
item.value = value;
item.comment = comment;

section->items.push_back(item);
} else {
fprintf(stderr, "解析参数失败[%s]\n", line.c_str());
}

comment = "";
}
}
fclose(fp);
return 0;
}

int IniFile::save() { return saveas(fname_); }

int IniFile::saveas(const string &filename) {
string data = "";

for (iterator sect = sections_.begin(); sect != sections_.end(); ++sect) {
if (sect->second->comment != "") {
data += sect->second->comment;
data += delim;
}

if (sect->first != "") {
data += string("[") + sect->first + string("]");
data += delim;
}

for (IniSection::iterator item = sect->second->items.begin();
item != sect->second->items.end(); ++item) {
if (item->comment != "") {
data += item->comment;
data += delim;
}

data += item->key + "=" + item->value;
data += delim;
}
}

FILE *fp = fopen(filename.c_str(), "w");

fwrite(data.c_str(), 1, data.length(), fp);

fclose(fp);

return 0;
}
IniSection *IniFile::getSection(const string &section /*=""*/) {
iterator it = sections_.find(section);

if (it != sections_.end()) {
return it->second;
}

return NULL;
}

string IniFile::getStringValue(const string &section, const string &key,
int &ret) {
string value, comment;

ret = getValue(section, key, value, comment);

return value;
}

int IniFile::getIntValue(const string &section, const string &key, int &ret) {
string value, comment;

ret = getValue(section, key, value, comment);

return atoi(value.c_str());
}

double IniFile::getDoubleValue(const string &section, const string &key,
int &ret) {
string value, comment;

ret = getValue(section, key, value, comment);

return atof(value.c_str());
}

int IniFile::getValue(const string &section, const string &key, string &value) {
string comment;
return getValue(section, key, value, comment);
}
int IniFile::getValue(const string &section, const string &key, string &value,
string &comment) {
IniSection *sect = getSection(section);

if (sect != NULL) {
for (IniSection::iterator it = sect->begin(); it != sect->end(); ++it) {
if (it->key == key) {
value = it->value;
comment = it->comment;
return RET_OK;
}
}
}

return RET_ERR;
}
int IniFile::getValues(const string &section, const string &key,
vector<string> &values) {
vector<string> comments;
return getValues(section, key, values, comments);
}
int IniFile::getValues(const string &section, const string &key,
vector<string> &values, vector<string> &comments) {
string value, comment;

values.clear();
comments.clear();

IniSection *sect = getSection(section);

if (sect != NULL) {
for (IniSection::iterator it = sect->begin(); it != sect->end(); ++it) {
if (it->key == key) {
value = it->value;
comment = it->comment;

values.push_back(value);
comments.push_back(comment);
}
}
}

return (values.size() ? RET_OK : RET_ERR);
}
bool IniFile::hasSection(const string &section) {
return (getSection(section) != NULL);
}

bool IniFile::hasKey(const string &section, const string &key) {
IniSection *sect = getSection(section);

if (sect != NULL) {
for (IniSection::iterator it = sect->begin(); it != sect->end(); ++it) {
if (it->key == key) {
return true;
}
}
}

return false;
}
int IniFile::getSectionComment(const string &section, string &comment) {
comment = "";
IniSection *sect = getSection(section);

if (sect != NULL) {
comment = sect->comment;
return RET_OK;
}

return RET_ERR;
}
int IniFile::setSectionComment(const string &section, const string &comment) {
IniSection *sect = getSection(section);

if (sect != NULL) {
sect->comment = comment;
return RET_OK;
}

return RET_ERR;
}

int IniFile::setValue(const string &section, const string &key,
const string &value, const string &comment /*=""*/) {
IniSection *sect = getSection(section);

string comt = comment;

if (comt != "") {
comt = flags_[0] + comt;
}

if (sect == NULL) {
sect = new IniSection();

if (sect == NULL) {
fprintf(stderr, "no enough memory!\n");
exit(-1);
}

sect->name = section;
sections_[section] = sect;
}

for (IniSection::iterator it = sect->begin(); it != sect->end(); ++it) {
if (it->key == key) {
it->value = value;
it->comment = comt;
return RET_OK;
}
}

// not found key
IniItem item;
item.key = key;
item.value = value;
item.comment = comt;

sect->items.push_back(item);

return RET_OK;
}
void IniFile::getCommentFlags(vector<string> &flags) { flags = flags_; }
void IniFile::setCommentFlags(const vector<string> &flags) { flags_ = flags; }
void IniFile::deleteSection(const string &section) {
IniSection *sect = getSection(section);

if (sect != NULL) {

sections_.erase(section);
delete sect;
}
}
void IniFile::deleteKey(const string &section, const string &key) {
IniSection *sect = getSection(section);

if (sect != NULL) {
for (IniSection::iterator it = sect->begin(); it != sect->end(); ++it) {
if (it->key == key) {
sect->items.erase(it);
break;
}
}
}
}

void IniFile::release() {
fname_ = "";

for (iterator i = sections_.begin(); i != sections_.end(); ++i) {
delete i->second;
}

sections_.clear();
}

bool IniFile::isComment(const string &str) {
bool ret = false;

for (size_t i = 0; i < flags_.size(); ++i) {
size_t k = 0;

if (str.length() < flags_[i].length()) {
continue;
}

for (k = 0; k < flags_[i].length(); ++k) {
if (str[k] != flags_[i][k]) {
break;
}
}

if (k == flags_[i].length()) {
ret = true;
break;
}
}

return ret;
}
// for debug
void IniFile::print() {
printf("filename:[%s]\n", fname_.c_str());

printf("flags_:[");

for (size_t i = 0; i < flags_.size(); ++i) {
printf(" %s ", flags_[i].c_str());
}

printf("]\n");

for (iterator it = sections_.begin(); it != sections_.end(); ++it) {
printf("section:[%s]\n", it->first.c_str());
printf("comment:[%s]\n", it->second->comment.c_str());

for (IniSection::iterator i = it->second->items.begin();
i != it->second->items.end(); ++i) {
printf(" comment:%s\n", i->comment.c_str());
printf(" parm :%s=%s\n", i->key.c_str(), i->value.c_str());
}
}
}

void IniFile::trimleft(string &str, char c /*=' '*/) {
// trim head
int len = str.length();

int i = 0;

while (str[i] == c && str[i] != '\0') {
i++;
}

if (i != 0) {
str = string(str, i, len - i);
}
}

void IniFile::trimright(string &str, char c /*=' '*/) {
// trim tail
int i = 0;
int len = str.length();

for (i = len - 1; i >= 0; --i) {
if (str[i] != c) {
break;
}
}
str = string(str, 0, i + 1);
}
void IniFile::trim(string &str) {
// trim head

int len = str.length();

int i = 0;

while (isspace(str[i]) && str[i] != '\0') {
i++;
}

if (i != 0) {
str = string(str, i, len - i);
}
// trim tail
len = str.length();

for (i = len - 1; i >= 0; --i) {
if (!isspace(str[i])) {
break;
}
}
str = string(str, 0, i + 1);
}
} // namespace inifile
#endif

程序运行结果

iniTest

------ 本文结束感谢您的阅读------
Donate a cup of cola?