首先包含fstream、string、map和sstream头文件,然后用ifstream打开配置文件并检查是否成功打开,接着逐行读取内容,使用stringstream解析每行的键值对,最后将键值存储到map或unordered_map中完成配置读取。
在C++中,使用fstream读取配置文件是一种常见且高效的方法。配置文件通常是纯文本格式,每行包含键值对,例如key=value。通过std::ifstream可以逐行读取并解析内容。
包含必要的头文件
要使用文件流操作,需包含以下头文件:
- #include <fstream>:用于文件输入输出
- #include <string>:处理字符串
- #include <map> 或 #include <unordered_map>:存储键值对
- #include <sstream>:用于字符串分割
打开并检查文件
使用std::ifstream打开配置文件,并验证是否成功:
std::ifstream file("config.txt"); if (!file.is_open()) { std::cerr << "无法打开配置文件!" << std::endl; return -1; }
确保文件路径正确,否则会因打不开文件导致读取失败。
立即学习“C++免费学习笔记(深入)”;
逐行解析键值对
读取每一行,查找等号=分隔键和值:
std::map<std::string, std::string> config; std::string line; while (std::getline(file, line)) { // 忽略空行或注释(以#开头) if (line.empty() || line[0] == '#') continue; size_t pos = line.find('='); if (pos != std::string::npos) { std::string key = line.substr(0, pos); std::string value = line.substr(pos + 1); // 去除前后空白 key.erase(0, key.find_first_not_of(" t")); key.erase(key.find_last_not_of(" t") + 1); value.erase(0, value.find_first_not_of(" t")); value.erase(value.find_last_not_of(" t") + 1); config[key] = value; } } file.close();
这样就能把配置项存入map中,后续通过config[“port”]等方式访问。
使用配置值
读取完成后,可以直接使用存储的值:
if (config.find("port") != config.end()) { int port = std::stoi(config["port"]); std::cout << "端口:" << port << std::endl; }
注意对数值类型做转换时使用std::stoi、std::stod等,并考虑异常处理。
基本上就这些。只要文件格式简单规范,用fstream读取配置并不复杂,关键是做好格式判断和字符串清理。不复杂但容易忽略细节比如空格和注释处理。
c++ 配置文件 键值对 red String include 字符串 ifstream fstream 值类型 map