配置文件读取的简要C/C++代码
来源:互联网 发布:usleep函数源码 编辑:程序博客网 时间:2024/05/18 01:50
经常涉及到配置文件, 经常要用, 来写个代码, 欢迎挑刺指正, 环境是linux/g++, 代码如下(配置文件的每行用"="分割):
#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.
阅读全文
1 0
- 配置文件读取的简要C/C++代码
- 配置文件的读取,纯C代码
- C语言读取配置文件代码
- samba unix风格的配置文件配置信息读取C代码.
- Linux C代码实现读取配置文件示例
- C 读取配置文件函数
- C读取配置文件
- C语言读取配置文件
- linux c读取配置文件
- C语言读取配置文件
- C语言读取配置文件
- linux c 读取配置文件
- C语言读取配置文件
- 网上找的c语言读取配置文件
- C语言读取配置文件的另类写法
- Linux下配置文件读取操作流程及其C代码实现
- Linux下配置文件读取操作流程及其C代码实现
- 【C/C++】C语言读取简单配置文件
- nextint()方法的一个小细节分享
- YII2框架学习 安全篇(二) XSS攻击和防范(下)
- JAVA基础-引用数据类型与判断循环
- HttpRuntime.Cache .Net自带的缓存类
- Java对象克隆(复制):深复制和浅复制
- 配置文件读取的简要C/C++代码
- codeforces160A
- Linux下几种文件传输命令
- C#对象深度克隆
- ajax一些常见问题
- 了解VPN, NAT, 代理服务器的原理
- IOS 用数学方程组思路理解 约束
- Service启动流程-startService
- MYSQL主备同步问题(1032 1036)解决方法