c++读取配置文件方法

c++读取配置文件方法

2023年7月7日发(作者:)

c++读取配置⽂件⽅法⼀。消息头⽂件内容如下:// stdafx.h : 标准系统包含⽂件的包含⽂件,// 或是经常使⽤但不常更改的// 特定于项⽬的包含⽂件//#pragma once#include "targetver.h"#include #include #ifndef _GET_CONFIG_H_#define _GET_CONFIG_H_

#include #include using namespace std;

#define COMMENT_CHAR '#'

bool ReadConfig(const string & filename, map & m);void PrintConfig(const map & m);#endif⼆。 代码:// : 定义控制台应⽤程序的⼊⼝点。//#include "stdafx.h"#include #include using namespace std;bool IsSpace(char c){ if (' ' == c || 't' == c) return true; return false;}void Trim(string & str){ if (()) { return; } int i, start_pos, end_pos; for (i = 0; i < (); ++i) { if (!IsSpace(str[i])) { break; } } if (i == ()) { // 全部是空⽩字符串 str = ""; return; }

start_pos = i;

for (i = () - 1; i >= 0; --i) { if (!IsSpace(str[i])) { break; } } end_pos = i;

str = (start_pos, end_pos - start_pos + 1);}bool AnalyseLine(const string & line, string & key, string & value){ if (()) return false; int start_pos = 0, end_pos = () - 1, pos; if ((pos = (COMMENT_CHAR)) != -1) { if (0 == pos) { // ⾏的第⼀个字符就是注释字符 return false; } end_pos = pos - 1; } string new_line = (start_pos, start_pos + 1 - end_pos); // 预处理,删除注释部分

if ((pos = new_('=')) == -1) return false; // 没有=号

key = new_(0, pos); value = new_(pos + 1, end_pos + 1- (pos + 1));

Trim(key); if (()) { return false; } Trim(value); return true;}bool ReadConfig(const string & filename, map & m){ (); ifstream infile(filename.c_str()); if (!infile) { cout << "file open error" << endl; return false; } string line, key, value; while (getline(infile, line)) { if (AnalyseLine(line, key, value)) { m[key] = value; } }

(); return true;}void PrintConfig(const map & m){ map::const_iterator mite = (); for (; mite != (); ++mite) { cout << mite->first << "=" << mite->second << endl; }}int main(){ map m; ReadConfig("", m); PrintConfig(m);

system("pause"); return 0;}三。 配置⽂件名称为 内容如下:root = etcconfig = etc/profile

ProGroupName = branchreceive

四。执⾏结果截图

发布者:admin,转转请注明出处:http://www.yc00.com/news/1688702185a163774.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信