codice:
// Parse.hpp
#ifndef PARSE_HPP_
#define PARSE_HPP_
#include "Define.hpp"
#include <cstdio>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <cstring>
using namespace std;
N_BEG
/**
Name:SInfo \n
Author:Kleidemos \n
Description:Configurazione \n
*/
typedef struct SInfo
{
string key;
string value;
} Info;
/**
Name:CParse \n
Author:Kleidemos \n
Description:Parser classs for generic text \n
*/
class CParse
{
public:
CParse(){ _filename = "prog.conf"; };
CParse(string name){ _filename = name; };
CParse(char * name){ _filename = name; };
~CParse(){};
virtual void Read(char separator = 'v');
virtual void Write(char separator = 'v', string key = "", string value = "");
void Test();
virtual string Find(string key);
private:
string _filename;
vector<Info> conf;
};
N_END
#endif
codice:
// Parse.cpp
#include "Parse.hpp"
N_BEG
/**
Name:Read\n
Return: -\n
Argoments: A separator [ DEFAULT: v ] \n
Description:Puts a generic config into internal buffer\n
*/
void CParse::Read(char separator)
{
ifstream IN(_filename.c_str());
char code;
string key, value;
Info inf;
while(IN)
{
IN >> code;
if(code == separator) // a key find
{
IN >> key >> value;
inf.value = value;
inf.key = key;
conf.push_back(inf);
}
/**
Exclude:
- ;, # For comment
*/
else
{
key = " ";
value = " ";
// conf.push_back(inf);
}
}
IN.close();
}
/**
Name:Write\n
Return:-\n
Argoments:
- The name of options
- The value\n
- A separator [ DEFAULT: v ]
Description:Write a generic config value
*/
void CParse::Write(char separator, string key, string value)
{
ofstream OUT(_filename.c_str(), ios::app);
OUT << separator << " " << key << " " << value << "\n";
OUT.close();
}
/**
Name:Find\n
Return:A Value of option\n
Argoments: The name of option \n
Description: Findo a option\n
*/
string CParse::Find(string key)
{
string ret;
vector<Info>::iterator It = conf.begin();
for(; It != conf.end();++It)
{
if(It->key == key)
ret = It->value;
}
return ret;
}
/**
Name:Test\n
Return:-\n
Argoments: -
Description: Test the class\n
ONLY FOR DEBUG
*/
void CParse::Test()
{
// Inserting
Write('v', "prova", "si"); // write prova
Write('v', "provas", "no");// write provas
Write('v', "Schermo", "1024x768");// write Schermo
Write('n', "Schermos", "1024x768");// write error value
// Reading
Read('v'); // puts read file
// Printing
typedef vector<Info>::iterator It;
It it = conf.begin();
for(;it != conf.end();++it) // iterator
{
cout << it->key << " => " << it->value << "\n";
}
// Finding
cout << "Finding prova => " << Find("prova") << "\n";
cout << "Finding provas => " << Find("provas") << "\n";
cout << "Finding Schermo => " << Find("Schermo") << "\n";
cout << "Finding Schermos => " << Find("Schermos") << "\n";// try to find error value
}
N_END