这是一个类,直接调用就可以了。
H
class common_tool { public: common_tool(void); ~common_tool(void); std::string read_config(const char* filename,const char* parent_start,const char* parent_end,const char* child_start,const char* child_end); /* 判断在一个字符串里面是否存在查找的字符串 key 查找字符串 */ const bool exist_parent_key(const char* source,const char* key); /* 得到2个字符串中间的值 */ std::string get_value_between(const char* source,const char* keyname_start,const char* keyname_end); };
CPP
#include <iostream> #include <fstream> #include <string> #include "common_tool.h" using namespace std; common_tool::common_tool(void) { } common_tool::~common_tool(void) { } std::string common_tool::read_config(const char* filename,const char* child_end) { string strEmptyString=""; ifstream file(filename,ios::in); if (!file.is_open()) { return strEmptyString; } string line_string=""; string document_txt=""; int pos=-1; string keyname_parent_start = parent_start; string keyname_parent_end =parent_end; string keyname_child_start = child_start; string keyname_child_end = child_end; string keyvalue = ""; bool find_parent_start =false; bool find_parent_end =false; bool find_parent =false; while(getline(file,line_string)) { //find start of parent keyname if(false == find_parent) { find_parent_start = exist_parent_key(line_string.c_str(),keyname_parent_start.c_str()); if(true == find_parent_start) { find_parent = true; } } // find end of parent keyname find_parent_end = exist_parent_key(line_string.c_str(),keyname_parent_end.c_str()); if(true == find_parent_end) { find_parent = false; break; } //find keyvalue by keyname what you want in parent keyname. if(true == find_parent) { keyvalue=""; keyvalue.append(get_value_between(line_string.c_str(),keyname_child_start.c_str(),keyname_child_end.c_str())); if(keyvalue.length()>0) { break; } } } file.close(); return keyvalue; } const bool common_tool::exist_parent_key(const char* source,const char* key) { bool rs = false; string keyname = key; string line = source; int pos = 0; pos=line.find(key,0); if(pos<0) { rs = false; } else { rs = true; } return rs; } std::string common_tool::get_value_between(const char* source,const char* keyname_end) { bool rs = false; string str_source = source; string keyvalue = ""; static const char* str_empty_value = ""; int pos_start = 0; int pos_end = 0; int len = 0; len = str_source.length(); if(len<=0) { return str_empty_value; } pos_start = str_source.find(keyname_start,0); pos_end = str_source.find(keyname_end,0); if(pos_start<0 || pos_end <0) { return str_empty_value; // can not find! } int pos_keyvalue_start = pos_start + strlen(keyname_start); int len_keyvalue = pos_end - pos_keyvalue_start;//len - pos_keyvalue_start - strlen(keyname_end); if(len_keyvalue<=0) { return str_empty_value; } keyvalue = str_source.substr(pos_keyvalue_start,len_keyvalue); return keyvalue; }
完。
原文链接:https://www.f2er.com/xml/299287.html