#ifndef __SEC_FILE_H__
#define __SEC_FILE_H__
#include <string>
#include <vector>
#include <map>
using std::string;
using std::map;
using std::vector;
class SecFile
{
private:
string path;
static const char secComment = '#';
vector<string> vFile;
public:
int load(string path);
string getPath();
int getSec(string tag, vector<string>& vSec);
int getMaps(string tag, map<string, string>& mKVs);
int getKets(string tag, vector<string>& vKets);
string getValue(string tag, string ket);
string secToLine(string tag);
};
#endif //__SEC_FILE_H__
#include "secfile.h"
#include "stringutil.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int SecFile::load(string path)
{
this->path = path;
ifstream infile(path.c_str());
if ( ! infile)
{
cout << "not this file" + path << endl;
return -1;
}
int rowCount = 0;
string line;
while (getline(infile, line))
{
line = StringUtil::Trim(line);
if (this->secComment == line[0] || line.length() == 0)
continue;
this->vFile.push_back(line);
++rowCount;
}
infile.close();
return rowCount;
}
string SecFile::getPath()
{
return this->path;
}
int SecFile::getSec(string tag, vector<string>& vSec)
{
const string sBeg("<"+tag+">");
const string sEnd("</"+tag+">");
vector<string>::const_iterator ix = this->vFile.begin();
for ( ; this->vFile.end() != ix; ++ix )
{
if ( 0 == sBeg.compare((*ix).substr(0,sBeg.size())) )
{
++ix;
break;
}
}
if (this->vFile.end() == ix) return -1;
for (int rowCount = 0 ;ix != vFile.end(); ++ix )
{
if (sEnd == *ix) return rowCount;
vSec.push_back(*ix);
++rowCount;
}
return -1;
}
int SecFile::getKets(string tag, vector<string>& vKets)
{
string ket;
int ketCount = 0;
vector<string> vSec;
this->getSec(tag,vSec);
vector<string>::const_iterator ix = vSec.begin();
for ( ; ix != vSec.end(); ++ix )
{
ket = (*ix).substr(0, (*ix).find('='));
ket = StringUtil::Trim(ket);
vKets.push_back(ket);
++ketCount;
}
return ketCount;
}
string SecFile::getValue(string tag, string ket)
{
vector<string> vSec;
this->getSec(tag,vSec);
vector<string>::const_iterator ix = vSec.begin();
for ( ; ix != vSec.end(); ++ix )
{
if ((*ix).substr(0, ket.length()) == ket)
{
string value = (*ix).substr((*ix).find('=') + 1 );
value = StringUtil::Trim(value);
return value;
}
}
return "";
}
int SecFile::getMaps(string tag, map<string, string>& mKVs)
{
vector<string> vSec;
this->getSec(tag,vSec);
string ket;
string value;
int iCount = 0;
vector<string>::const_iterator ix = vSec.begin();
for ( ; ix != vSec.end(); ++ix )
{
ket = (*ix).substr(0, (*ix).find('='));
ket = StringUtil::Trim(ket);
value = (*ix).substr((*ix).find('=') + 1 );
value = StringUtil::Trim(value);
mKVs.insert(make_pair(ket,value));
iCount++;
}
return iCount;
}
string SecFile::secToLine(string tag)
{
vector<string> vSec;
if (this->getSec(tag, vSec) == -1) return "";
vector<string>::const_iterator ix = vSec.begin();
string sLine = *(ix++);
for ( ;ix != vSec.end(); ++ix )
{
sLine = sLine + " " + *ix;
}
return sLine;
}