Prova con questa mia classe:
codice:
// Parse.hpp
#ifndef PARSE_HPP_
#define PARSE_HPP_
#include <iostream>
#include <vector>
#include <fstream>
#include <string>
#include <map>
/**
Name:CParse \n
Author:Kleidemos \n
Description:Parser classs for generic text \n
*/
class CParse
{
public:
CParse(): _filename("prog.conf")
{ };
CParse(std::string name): _filename(name)
{ };
CParse(char * name): _filename(name)
{ };
~CParse(){};
/*
Permette di fare
string filename = <instanza>.FileConf()
o (per cambiarlo)
<instanza>.FileConf() = "prova"
*/
std::string& FileConf() { return _filename; };
void Read(const std::string &separator = "v");
void Write(const std::string &separator = "v", const std::string &key = "", const std::string &value = "");
void Test();
const std::string Find(const std::string &key);
private:
std::string _filename;
std::map<std::string, std::string> conf;
};
#endif
// Parse.cpp
#include "Parse.hpp"
/**
Name:Read\n
Return: -\n
Argouments: A separator [ DEFAULT: v ] \n
Description:Puts a generic config into internal buffer\n
*/
void CParse::Read(const string &separator)
{
std::ifstream in(_filename.c_str());
string code;
std::string key, value;
while(in)
{
in >> code;
if(code == separator) // a key find
{
in >> key >> value;
// inserisce i valori nella mappa
conf.insert(std::make_pair(key, value));
}
/*
Evito che valori diversi da quelli indicati da sepparator
vengano memorizzati.
Questo permette di usare commenti
*/
else
{
key = " ";
value = " ";
}
}
in.close();
}
/**
Name:Write\n
Return:-\n
Argouments:
- The name of options
- The value\n
- A separator [ DEFAULT: v ]
Description:Write a generic config value
*/
void CParse::Write(const std::string &separator, const std::string &key, const std::string &value)
{
std::ofstream out(_filename.c_str(), std::ios::app);
out << separator << " " << key << " " << value << "\n";
out.close();
}
/**
Name:Find\n
Return:A Value of option\n
Argouments: The name of option \n
Description: Find a option\n
*/
const std::string CParse::Find(const std::string &key)
{
return conf[key];
}
/**
Name:Test\n
Return:-\n
Argouments: -
Description: Test the class\n
ONLY FOR DEBUG
*/
void CParse::Test()
{
// Inserting
Write("dat", "prova", "si"); // write prova
Write("dat", "provas", "no");// write provas
Write("dat", "Schermo", "1024x768");// write Schermo
Write("so", "Schermos", "1024x768");// write error value
Write("no", "Schermos", "1024x768");// write error value
// Reading
Read("dat"); // puts read file
// 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
}