利用string实现配置文件

    xiaoxiao2024-12-29  63

    //字符串trim函数 string trim(const string& str) {     string t = "    abd  cdi   783     ";    //示例字符串     t.erase(0, t.find_first_not_of(" \t\n\r"));     // "abd cdi   783     "      erase(int i,int j)是擦除从i到j的所有字符(含i,j位)     t.erase(t.find_last_not_of(" \t\n\r") + 1);   // "abd cdi   783"          erase(int n)是擦除第n位置以后(含第n位置)的所有字符     return t; } 

    注:find_first_not_of(" \t\n\r")返回第一个不是这些字符(空格、制表符、换行、回车)的字符的位置

    find_last_not_of函数则是返回从右往左数第一个符合条件的字符

     

    //字符串分割函数 vector<string> split(string str,string pattern){     string::size_type pos;     vector<std::string> result;     str+=pattern;//扩展字符串以方便操作     int size=str.size();

        for(int i=0; i<size; i++)    {         pos=str.find(pattern,i);         if(pos<size){             std::string s=str.substr(i,pos-i);             s=trim(s);             result.push_back(s);             i=pos+pattern.size()-1;         }     }     return result; }

     

    //此处实现一个简单的配置文件读取操作,比定义宏编译速度快 bool LoadFromFile(const string &account_info_file){     //打开文件     ifstream fin;     fin.open(account_info_file.c_str());     if (!fin){         printf("get account info failed \n\t may be the file %s not exist!\n",account_info_file.c_str());         return false;     }

        //按行遍历     string line;     while(getline(fin,line)){         line = trim(line);         //为空或首字符为"#",则忽略         if (line.empty() || line[0] == '#' ){             continue;         }

            vector<string> key_value = split(line,"=");         if (stricmp(key_value[0].c_str(),SELF_DEFINE_STRING_CONFIG) == 0){    //SELF_DEFINE_STRING_CONFIG是键值对的key,而self_define_string_config_是键值对的value             string self_define_string_config_ = key_value[1];         }

        //关闭文件     fin.close();     return true; }

    最新回复(0)