写一个INIReader.h
时间: 2024-05-11 12:18:24 浏览: 10
以下是一个简单的INIReader.h的实现,用于读取INI文件中的键值对:
```c++
#ifndef INIREADER_H
#define INIREADER_H
#include <string>
#include <map>
class INIReader
{
public:
INIReader(const std::string& filename);
std::string Get(const std::string& section, const std::string& name, const std::string& default_value = "") const;
private:
std::map<std::string, std::map<std::string, std::string>> data_;
};
#endif // INIREADER_H
```
实现细节:
1. 构造函数会读取INI文件中的所有键值对,并将它们存储在一个二维的map中,其中第一层map的key是section名,第二层map的key是name名,value是对应的值。这个数据结构可以方便地进行查询。
2. Get方法可以根据给定的section和name查找对应的值。如果找到了就返回对应的值,否则返回默认值。
下面是INIReader.cpp的实现:
```c++
#include "INIReader.h"
#include <fstream>
#include <algorithm>
INIReader::INIReader(const std::string& filename)
{
std::ifstream file(filename);
std::string line;
std::string current_section = "";
while (std::getline(file, line))
{
// 去掉行首和行尾的空格
line.erase(std::remove_if(line.begin(), line.end(), ::isspace), line.end());
if (line.empty() || line[0] == ';') // 空行或注释行
{
continue;
}
else if (line[0] == '[' && line[line.size() - 1] == ']') // section
{
current_section = line.substr(1, line.size() - 2);
}
else // name-value pair
{
auto pos = line.find('=');
if (pos != std::string::npos)
{
std::string name = line.substr(0, pos);
std::string value = line.substr(pos + 1);
data_[current_section][name] = value;
}
}
}
}
std::string INIReader::Get(const std::string& section, const std::string& name, const std::string& default_value) const
{
auto it1 = data_.find(section);
if (it1 != data_.end())
{
auto it2 = it1->second.find(name);
if (it2 != it1->second.end())
{
return it2->second;
}
}
return default_value;
}
```
实现细节:
1. 构造函数中使用了std::getline从文件中读取每一行,并使用std::isspace和std::remove_if去掉行首和行尾的空格。
2. 如果是空行或注释行,就直接跳过。
3. 如果是[section]行,就更新当前的section名。
4. 如果是name=value行,就将它存储在data_中对应的section和name下。
5. Get方法中首先查找给定的section是否存在,如果存在则在该section中查找给定的name是否存在,如果存在就返回对应的值,否则返回默认值。