目前只是实现了简单的读取整型和字符串,如果串是由“”扩住的,会连“”也返回。有空再改为不连“”一起返回。
#pragma once #include <map> using namespace std; class ReadIni { public: ReadIni(void); ReadIni(char *); int ReadInt(const char*,const char*); char* ReadString(const char*,const char*); public: virtual ~ReadIni(void); private: bool AnalyseIni(); void StripLeadingAndTrailingBlanks(string&); bool CheckDigit(const string&); void ValidSectName(const string&,const string&); private: char m_fileName[256]; char m_value[1024]; map<string,map<string,string> > m_iniMap; }; #include "StdAfx.h" #include "ReadIni.h" #include <stdlib.h> #include <string.h> #include <string> #include <iostream> #include <assert.h> ReadIni::ReadIni(void) { memset(m_fileName,0,sizeof(m_fileName)); memset(m_value,0,sizeof(m_value)); } ReadIni::~ReadIni(void) { } ReadIni::ReadIni(char *fileName) { strncpy(m_fileName,fileName,sizeof(m_fileName)-1); AnalyseIni(); } int ReadIni::ReadInt(const char* sect, const char* name) { string sectStr=sect; string nameStr=name; ValidSectName(sectStr,nameStr); strncpy(m_value,(m_iniMap[sectStr][name]).c_str(),sizeof(m_value)); if (!CheckDigit(m_value)) { printf("The m_value is not digit:%s!/n",m_value); assert(false); } return atoi(m_value); } char* ReadIni::ReadString(const char* sect,const char* name) { string sectStr=sect; string nameStr=name; ValidSectName(sectStr,nameStr); strncpy(m_value,(m_iniMap[sectStr][name]).c_str(),sizeof(m_value)); return m_value; } bool ReadIni::AnalyseIni() { FILE *fp = fopen(m_fileName, "r+"); if (NULL == fp) { printf("Can't open file %s/n",m_fileName); return false; } char buf[1024]={0}; string sectStr=""; while (NULL != fgets(buf,sizeof(buf)-1,fp)) { string lineStr=buf; StripLeadingAndTrailingBlanks(lineStr); if ((lineStr[0] == ';') || (lineStr == "")) { continue; } if (lineStr[0] == '[') { sectStr = lineStr.substr(1,lineStr.rfind(']')-1); } else { if (sectStr == "") { printf("Wrong file,No section before name!/n"); assert(false); } string name=lineStr.substr(0,lineStr.find('=')); string value=lineStr.substr(lineStr.find('=')+1); m_iniMap[sectStr][name]=value; //cout<<m_iniMap[sectStr][name]<<endl; } } return true; } void ReadIni::StripLeadingAndTrailingBlanks(string& StringToModify) { if(StringToModify.empty()) return; int startIndex = StringToModify.find_first_not_of(" /t/n"); int endIndex = StringToModify.find_last_not_of(" /t/n"); string tempString = StringToModify; StringToModify.erase(); if(-1 == startIndex) StringToModify = ""; else StringToModify = tempString.substr(startIndex, (endIndex-startIndex+ 1) ); } bool ReadIni::CheckDigit(const string&str) { for(int i=0; i<str.size(); i++) if(!isdigit(str[i])) return false; return true; } void ReadIni::ValidSectName(const string& sect,const string& name) { if (!m_iniMap.count(sect)) { printf("Not section %s/n",sect.c_str()); assert(false); } else { if (!m_iniMap[sect].count(name)) { printf("Not name %s/n",name.c_str()); assert(false); } } return ; }