运用链表读写配置文件。
可以保存配置文件中的注解。
ConfigParser.h
#ifndef linux
#pragma once
#else
#include <string.h>
#define _stricmp strcasecmp
#endif // linux
#include <string>
using std::string;
typedef struct Options
{
string comment; // save option notes.
string name; // save option name.
string value; // save option value.
Options* next;
}*pOption, Option;
typedef struct Sections
{
string comment; // save section notes.
string name; // section name.
Option *options;
Sections* next;
}*pSection, Section;
class ConfigParser
{
private:
string _ini;
Section *_section_list_head;
size_t section_count = 0;
string line_break = "\n";
public:
ConfigParser(string path);
~ConfigParser();
// Init Section struct.
Section* InitSectionList();
// read part
bool ReadIni();
string GetString(const string& root, const string& key, const string& def = "");
int GetInt(const string& root, const string& key, int def = 0);
bool GetBool(const string& root, const string& key, bool def = false);
double GetDouble(const string& root, const string& key, double def = 0.00);
// set ini
void SetValue(const string& root, const string& key, const string& value);
// void SetString(const string& root, const string& key, const string& value);
void SetInt(const string& root, const string& key, int value);
void SetDouble(const string& root, const string& key, double value);
void SetBool(const string& root, const string& key, bool value);
// write ini
bool WriteIni(string path);
// Is notes
bool IsNotes(string line);
bool IsSection(string line);
bool IsExistSection(string root);
bool IsExistOption(string root, string option);
string TrimLeadTrailSpecStr(string src, string keyword);
string TrimLeadSpecStr(string src, string keyword);
string TrimTrailSpecStr(string src, string keyword);
// delete '\r' & '\n' at the end of the string.
string TrimTrialLineBreak(string data);
void AddSection(string section, string note);
void AddOption(string section, string option, string value, string note);
void ViewSections();
};
ConfigParser.cpp
#include "ConfigParser.h"
#include <iostream>
#include <fstream>
#include <sstream>
using std::fstream;
using std::stringstream;
using std::istringstream;
using std::to_string;
using std::ios;
using std::cout;
using std::endl;
ConfigParser::ConfigParser(string path)
{
_ini = path;
ReadIni();
}
ConfigParser::~ConfigParser()
{
for (size_t index = 0; index < section_count; index++)
{
Section* node = _section_list_head;
_section_list_head = _section_list_head->next;
Option* op_head = node->options;
size_t j = 0;
while (op_head != nullptr)
{
Option* child = op_head;
op_head = op_head->next;
// cout << child->name <<" free." << j++ << endl;
delete child;
}
delete node;
// cout << "delete