雷火电竞-中国电竞赛事及体育赛事平台

歡迎來到入門教程網(wǎng)!

C語言

當前位置:主頁 > 軟件編程 > C語言 >

c++實現(xiàn)逐行讀取配置文件寫入內(nèi)存的示例

來源:本站原創(chuàng)|時間:2020-01-10|欄目:C語言|點擊:

不解析配置內(nèi)容,只讀取文件內(nèi)容,剪去注釋和首尾空格后寫入緩存: vector<string> 中。供其他方法使用。
代碼是在做一個MFC小工具時寫的。

ReadProtocol.h

復制代碼 代碼如下:

/**
* 從文件中 讀取 protocol 的內(nèi)容 寫入緩存
* 供外部方法使用
* Alex Liu, 2014
*/

#pragma once


#include <vector>
#include <map>
#include <list>
#include <string>

using namespace std;


#define MAX_FILEPATH 512

#define COMMENT_FLG '#'
#define SECTION_BEGIN_FLG '['
#define SECTION_END_FLG  ']'

class ReadProtocol {
public:
 ReadProtocol(char* FilePath);
 ~ReadProtocol();

 /**
 * 返回值為 errMsg 的地址 為了方便鏈式調(diào)用
 * 缺省返回 "成功"
 */
 char* GetErrInfo(char* errMsg, int errNo = 0);
 /**
 * 逐行讀取文件內(nèi)容 寫入 m_StrVect
 * 使用 vector::push_back() 寫入
 * return 0 成功 < 0 失敗 可根據(jù)返回值 GetErrInfo
 */
 int ReadIniFile();

 /**
 * 獲取根據(jù)目錄獲取一個
 * 使用 vector::push_back() 寫入
 * return 0 成功 < 0 失敗 可根據(jù)返回值 GetErrInfo
 */
 int GetOneSection(string Section, list<string> &Protocol);

private:
 void PushBackToVector(string oneLine);

private:
 char m_IniFile[MAX_FILEPATH];
 string m_ErrPos;

 map<string, unsigned int> m_SectionMap;
 vector<string> m_StrVect;
};

ReadProtocol.cpp

復制代碼 代碼如下:

//

//#include "stdafx.h"
#include <fstream>

#include "ReadProtocol.h"

//去掉字符串首尾的空格
static string strTrim(string aStr)
{
    string s = aStr;
    unsigned int first, last;
    if (string::npos != (first = s.find_first_not_of(' ') ))
        s = s.substr(first, s.length()-first);
    if (string::npos != (last = s.find_last_not_of(' ') ))
        s = s.substr(0, last+1);
    return s;
}

///=====================================================================================

ReadProtocol::ReadProtocol(char* FilePath)
{
 int iLen = (strlen(FilePath) > MAX_FILEPATH) ? MAX_FILEPATH : strlen(FilePath);
 memset(m_IniFile, 0, MAX_FILEPATH);
 memcpy(m_IniFile, FilePath, iLen);
}

ReadProtocol::~ReadProtocol()
{
 m_SectionMap.clear();
 m_StrVect.clear();
}

int ReadProtocol::GetOneSection(string Section, list<string> &Protocol)
{
 unsigned int Start = 0;
 // 注意這里不能使用 [] 運算符
 map<string, unsigned int>::iterator itr = m_SectionMap.find(Section);
 if (m_SectionMap.end() == itr)
 {
  m_ErrPos = Section;
  return -5;   // Unknown Section!!
 }
 else
 {
  Start = itr->second;
 }


 vector<string>::iterator it = m_StrVect.begin() + Start + 1;
 for (; it!=m_StrVect.end(); ++it)
 {
  unsigned int First, Last;
  First = it->find_first_of ( SECTION_BEGIN_FLG );
  Last = it->find_last_of ( SECTION_END_FLG );
  // stop when the next Section
  if( string::npos != First && string::npos != Last)
  {
   break;
  }

  Protocol.push_back(*it);
 }
 return (int)Protocol.size();
}

int ReadProtocol::ReadIniFile()
{
 ifstream fin(m_IniFile);
 if (!fin.is_open())
 {
  return -1; //can'topen file
 }
 string strLine;
 unsigned int Last;

 while (std::getline(fin, strLine).good())
 {
  if ( string::npos !=(Last = strLine.find_last_not_of('\r') ))
  {
   //delete \r
   strLine = strLine.substr(0, Last + 1);
  }
  PushBackToVector(strLine);
 }
 fin.close();

 if (m_StrVect.empty())
 {
  return -2; //get noting from file
 }
 return 0;
}

void ReadProtocol::PushBackToVector(string oneLine)
{
 unsigned int uPos;
 //去掉行尾注釋
 if ( string::npos != (uPos = oneLine.find_first_of( COMMENT_FLG ) ) )
 {
  oneLine = oneLine.substr(0, uPos + 1);
 }
 //去首尾空格
 oneLine = strTrim(oneLine);
 if (oneLine.empty() || oneLine.length() < 2) return;

 //一行只能有一條記錄
 unsigned int First, Last;
 First = oneLine.find_first_of(SECTION_BEGIN_FLG);
 Last = oneLine.find_last_of(SECTION_END_FLG);
 // is Section
 if( string::npos != First && string::npos != Last)
 {
  m_SectionMap[ oneLine.substr(First + 1, Last - First - 1) ] = m_StrVect.size();
 }
 m_StrVect.push_back(oneLine);
}

char* ReadProtocol::GetErrInfo(char* errMsg, int errNo)
{
 string errInfo;
 switch (errNo)
 {
 case 0:
  {
   errInfo = "Success!";
   break;
  }
 case -1:
  {
   char Path[1024] = {0};
   int pLength = 1024;
   GetCurrentDirectory(pLength, Path);
   errInfo.append("Can't open file. The file name is:==>\"");
   errInfo.append( m_IniFile);
   errInfo.append("\"\r\nMaybe no such file in Path:");
   errInfo.append(Path);
   break;
  }
 case -2:
  {
   errInfo = "Get noting from file: ";
   errInfo.append(m_IniFile);
   break;
  }
 case -3:
  {
   errInfo = "Analyze file failed. In ==> ";
   errInfo.append(m_ErrPos);
   break;
  }
 case -5:
  {
   errInfo = "\r\nUnknown Section!! ==> \"[";
   errInfo.append(m_ErrPos);
   errInfo.append("]\"\r\n請檢查配置文件中是否有遺漏。");
   break;
  }
 default:
  {
   errInfo = "請按照正確步驟使用";
  }
 }
 memcpy(errMsg, errInfo.c_str(), errInfo.length());
 return errMsg;
}

上一篇:C語言十進制轉二進制代碼實例

欄    目:C語言

下一篇:c++傳遞函數(shù)指針和bind的示例

本文標題:c++實現(xiàn)逐行讀取配置文件寫入內(nèi)存的示例

本文地址:http://m.jygsgssxh.com/a1/Cyuyan/3655.html

網(wǎng)頁制作CMS教程網(wǎng)絡編程軟件編程腳本語言數(shù)據(jù)庫服務器

如果侵犯了您的權利,請與我們聯(lián)系,我們將在24小時內(nèi)進行處理、任何非本站因素導致的法律后果,本站均不負任何責任。

聯(lián)系QQ:835971066 | 郵箱:835971066#qq.com(#換成@)

Copyright © 2002-2020 腳本教程網(wǎng) 版權所有