写一个读写ini配置文件的c++
时间: 2024-01-21 16:03:12 浏览: 23
以下是一个简单的C++读写INI配置文件的示例代码:
```cpp
#include <iostream>
#include <fstream>
#include <string>
#include <map>
using namespace std;
map<string, string> read_ini_file(string filename) {
map<string, string> config;
ifstream file(filename);
if (file.is_open()) {
string line;
string section;
while (getline(file, line)) {
if (line.empty() || line[0] == ';' || line[0] == '#') {
continue;
}
if (line[0] == '[') {
section = line.substr(1, line.find(']') - 1);
continue;
}
size_t separator = line.find('=');
string key = line.substr(0, separator);
string value = line.substr(separator + 1);
config[section + "." + key] = value;
}
file.close();
}
return config;
}
void write_ini_file(string filename, map<string, string> config) {
ofstream file(filename);
if (file.is_open()) {
string current_section = "";
for (auto const& [key, value] : config) {
int separator = key.find('.');
string section = key.substr(0, separator);
string name = key.substr(separator + 1);
if (section != current_section) {
file << "[" << section << "]" << endl;
current_section = section;
}
file << name << "=" << value << endl;
}
file.close();
}
}
int main() {
// 读取配置文件
map<string, string> config = read_ini_file("config.ini");
// 输出配置项
for (auto const& [key, value] : config) {
cout << key << " = " << value << endl;
}
// 修改配置项
config["Section1.Key1"] = "new_value";
// 写入新的配置文件
write_ini_file("config_new.ini", config);
return 0;
}
```
该代码首先定义了一个`map<string, string>`类型的变量来存储INI配置文件中的内容。然后,`read_ini_file`函数用于从一个INI文件中读取配置项,并将结果存储在该变量中。`write_ini_file`函数用于将一个`map<string, string>`类型的变量中的内容写入到INI文件中。
在主函数中,我们首先读取了一个配置文件,然后输出了其中的所有配置项。接着,我们修改了其中一个配置项,并将其写入到了一个新的配置文件中。
需要注意的是,该代码只能处理简单的INI配置文件,即每个配置项都必须属于一个特定的节(section)。如果INI文件中存在无法处理的情况,例如没有明确的节名称,则该代码可能会出现错误。