ini_parse.ini
#include "ini_parse.h"
#include <iostream>
#include <fstream>
using namespace std;
IniParse::IniParse(const string &path) : path_(path)
{
ifstream ifs(path); // 打开配置文件
if (!ifs.is_open()) {
return;
}
string line;
string section;
while (!ifs.eof()) { // 逐行读取配置文件内容
getline(ifs, line);
Strip(line); // 去除开头和结尾的空格、制表符和换行符
if (line.empty() || line.front() == '#') { // 跳过空行和注释行
continue;
}
size_t index = line.find('='); // 查找等号索引
if (line.front() == '[' && line.back() == ']') { // 提取出配置项的名称
section = line.substr(1, line.size() - 2);
data_[section] = {}; // 空的unordered_map用于存储该配置项下的键值对
} else if (index != string::npos) { // 提取出键和值
string key = Strip(line.substr(0, index));
string value = Strip(line.substr(index + 1));
data_[section][key] = value; // 存储配置项和键值对
} else {
// TODO 不规范写法
}
}
ifs.close(); // 关闭配置文件
}
string IniParse::Strip(const string &src)
{
size_t left = src.find_first_not_of(" \t\n"); // 查找第一个非空字符的索引
size_t right = src.find_last_not_of(" \t\n"); // 查找最后一个非空字符的索引
if (left == string::npos || right == string::npos) {
return "";
}
return src.substr(left, right - left + 1); // 提取出非空子串
}
INI_DATA_TYPE IniParse::GetData()
{
return data_; // 返回解析后的配置数据
}
unordered_map<string, string> IniParse::GetValues(const string §ion)
{
return data_[section]; // 返回特定配置项下的键值对
}
string IniParse::GetValue(const string §ion, const string &option)
{
if (data_.find(section) == data_.end()) { // 验证配置项是否存在
return "";
}
return data_[section][option]; // 返回特定配置项和键的值
}
ini_pare.h
#ifndef CPP0717_INIPARSE_H
#define CPP0717_INIPARSE_H
#include <string>
#include <unordered_map>
typedef std::unordered_map<std::string, std::unordered_map<std::string, std::string>> INI_DATA_TYPE;
class IniParse {
public:
explicit IniParse(const std::string &path);
INI_DATA_TYPE GetData();
std::unordered_map<std::string, std::string> GetValues(const std::string §ion);
std::string GetValue(const std::string §ion, const std::string &option);
static std::string Strip(const std::string &src);
private:
std::string path_;
INI_DATA_TYPE data_;
};
#endif //CPP0717_INIPARSE_H
ini_parse_test.cpp
#include <iostream>
#include "ini_parse.h"
void test01()
{
IniParse ins("../ini_parse/config.ini"); // 创建IniParse对象
INI_DATA_TYPE data = ins.GetData(); // 获取解析后的INI文件数据
// 遍历数据,输出每个section和对应的键值对
for (const auto &item : data) {
cout << "------------------------------------------" << endl;
cout << "section: " << item.first << endl;
for (const auto &subItem : item.second) {
cout << subItem.first << " = " << subItem.second << endl;
}
cout << "------------------------------------------" << endl;
}
string ip = ins.GetValue("mysql", "ip"); // 获取指定section的特定键的值
cout << ip << endl;
}
int main()
{
test01();
return 0;
}
config.ini
# 注释; ini文件中主要由两部分section 和 option
[mysql]
ip = 127.0.0.1
port = 3306
username = root
password = root
db_name = mayibase
[linux]
ip = 192.168.5.13
username = root
password = root
[error_code]
1001 = username or passwd is wrong
1002 = inner error
1003 = file not find