zoukankan      html  css  js  c++  java
  • C++读取配置文件

    在牛人的指导下,和前一个版本有了较大改变。

    逐行读取配置文件,然后逐行解析~

    读取一次之后,将键值对存入map,之后都从map中去取,减少读取文件次数

    主要代码如下:

    /**
    * 
    * read config file, add <key,value> into map.
    * @param filepath (in)line text
    * @param return  
    *        -1:error,invalid line
    *        0:success
    *           
    */
    int INIReader::readFile(const wstring &filename) {
        std::string strFilename(filename.begin(), filename.end());
        wifstream infile(strFilename.c_str());
        wstring buffer;
        while (getline(infile, buffer)) {
            parseContentLine(buffer);
        }
    
        return 0;
    }
    
    /**
    * 
    * handle single line text,then add <key,value> into map.
    * @param filepath (in)line text
    * @param return  
    *        -1:error,invalid line
    *        0:success
    *           
    */
    int INIReader::parseContentLine(wstring &contentLine) {
        contentLine = trim(contentLine);
        if (contentLine.size() < 1) {
            return 0;   // blank line
        }
    
        if (contentLine.substr(0, 1) == ANNOTATION_SYMBOL1 
            || contentLine.substr(0, 1) == ANNOTATION_SYMBOL2) {
                return 0;   // comment
        }
    
        wstring::size_type equalPos = contentLine.find_first_of(L"=");
        wstring::size_type startPos = 0;
        wstring::size_type endPos = contentLine.size() - 1;
    
        if (equalPos <= startPos || equalPos > endPos) {
            return -1; // invalid line
        }
    
        wstring key = rtrim(contentLine.substr(startPos, equalPos ));
        wstring value = ltrim(contentLine.substr(equalPos + 1, endPos));
    
        paramMap.insert(std::make_pair(key, value));
    
        //std::wcout <<key <<"	" << value << std::endl;
        return 0;
    }

    点此下载整个代码工程

  • 相关阅读:
    python函数
    python数据类型补充,copy知识点及文件的操作
    python数据类型
    python介绍
    Linux基础2-2 基础文件管理命令
    Linux基础2-1 根文件系统分析
    Linux基础1-3 命令使用帮助的获取
    Linux基础1-2 ls、cd、date、clock、cal、echo、printf命令使用简介
    Linux基础1-1
    fastDFS环境搭建
  • 原文地址:https://www.cnblogs.com/yejg1212/p/3183876.html
Copyright © 2011-2022 走看看