配置文件读取的简要C/C++代码
2017-06-19 23:56
411 查看
经常涉及到配置文件, 经常要用, 来写个代码, 欢迎挑刺指正, 环境是linux/g++, 代码如下(配置文件的每行用"="分割):
验证OK.
#include <iostream> #include <map> #include <string> #include <fstream> using namespace std; void deleteAllMark(string &s, const string &mark) { unsigned int nMarkSize = mark.size(); while(1) { unsigned int pos = s.find(mark); if(pos == string::npos) { return; } s.erase(pos, nMarkSize); } } int getConfigInfoFromFile(const string &filename, map<string, string> &mapInfo) { ifstream in(filename.c_str()); string line; if(in) { while (getline (in, line)) // line不包含'\n' { // 去掉注释 unsigned int pos = line.find("//"); if(pos != string::npos) { line.erase(pos, line.size() - pos); } deleteAllMark(line, " "); deleteAllMark(line, "\t"); pos = line.find("="); if(pos == string::npos) { continue; } string key = line.substr(0, pos); string value = line.substr(pos, line.size() - pos); value.erase(0, 1); // 兼容Windows直接复制过来的文件(非常重要) unsigned int nSize = value.size(); if(nSize > 0 && value[nSize - 1] == '\r') { value = value.substr(0, nSize - 1); } if(!key.empty() && !value.empty()) { mapInfo[key] = value; } } return 0; } return -1; } int main() { string filename = "test.cfg"; map<string, string> mapInfo; int iRet = getConfigInfoFromFile(filename, mapInfo); if(iRet != 0) { cout << "file error" << endl; return -1; } for(map<string, string>::iterator it = mapInfo.begin(); it != mapInfo.end(); ++it) { cout << it->first << "=" << it->second << endl; } return 0; }
验证OK.
相关文章推荐
- windows下,c /c++实现磁盘扫描,结合配置文件,读取特定后缀文件目录代码
- windows下,c /c++实现磁盘扫描,结合配置文件,读取特定后缀文件目录代码
- windows下,c /c++实现磁盘扫描,结合配置文件,读取特定后缀文件目录代码
- ASP.NET 2.0 读取配置文件[INI](示例代码下载)
- 读取配置文件动态创建对象[C++]
- HTTP 错误 500.19 - Internal Server Error 错误代码 0x80070005 由于权限不足而无法读取配置文件
- java对【配置文件的读取】与【读配置文件时的路径问题】代码总结
- ASP.NET 2.0 读取配置文件[INI](示例代码下载)
- 引自MagicLinux的C代码简单配置文件读取功能(使用需修改)
- c/c++: 读取配置文件(文本)内容的简单实现
- (转)C++编写Config类读取配置文件
- C++读取配置文件
- ASP.NET 2.0 读取配置文件[INI](示例代码下载)
- ASP.NET 2.0 读取配置文件[INI](示例代码下载)
- C++编写Config类读取配置文件
- [导入]ASP.NET 2.0 读取配置文件[INI](示例代码下载)
- C++嵌入Lua读取配置文件
- ASP.NET 2.0 读取配置文件[INI](示例代码下载)
- TIF图像文件的读取(c++代码)
- C++读取配置文件