[c++] config file – wczytywanie zmiennych z pliku tekstowego

Podziel się:   Facebook   Google+   Twitter   GG   E-mail  

Problem: jak wczytać zmienne do c++ znajdujące się w pliku tekstowym a następnie używać ich w programie?

Rozwiązanie: utworzyć klasę, która wczyta plik tekstowy, przydzieli każdą przetworzoną wcześniej linię do dynamicznej tablicy, której kluczem będzie nazwa zmiennej.

Wykorzystanie:
zawartość pliku “plik_konfiguracyjny.txt
[html]opcja1 wartosc1
opcja2 wartosc2[/html]

deklaracja klasy:
[php]
using namespace std;
#include
#include “config.php”
[/php]

inicjacja klasy:
[php]config *opcje;opcje=new config(“plik_konfiguracyjny.txt”);
// lub
config opcje(“plik_konfiguracyjny.txt”);[/php]

odwołanie do konkretnej zmiennej:
[php]opcje->v(“opcja1”);
// lub
opcje[“opcja1”];[/php]

Kod klasy config.cpp

[php]
class config {
public:
struct rec {
public:
string name;
string v;
};

string operator[] (const string);

private:
string cfg_src;
rec *conf;
unsigned int conf_ile;

public:
config(string);
~config();
string v(string );
void add_tmp_config(string, string);
};

config::config(string _src=”config.txt”){ //constructor
this->cfg_src = _src;
fstream cfg_file;
string _opcja,_val;

/* czy mozna otworzyc plik */
cfg_file.open(this->cfg_src.c_str(), std::ios::in);
if ( ! cfg_file.is_open() ) return;
if(cfg_file.bad() || !cfg_file.good() ) return;

/* ile linijek */
int licznik=0;
string dane; //smieci
while (!cfg_file.eof()) {
++licznik;
getline(cfg_file,dane);
} –licznik;
cfg_file.close();
/* zapisz wszystkie linie do tablicy */
if (licznik>0)
this->conf = new rec[licznik];
this->conf_ile = licznik;

if (licznik>0) { // sa rekordy
cfg_file.open(this->cfg_src.c_str(), std::ios::in);

for (unsigned int i=0;iconf_ile;i++) {//foreach file
if (cfg_file.eof()) return;
cfg_file >> _opcja;

// _val moze byc puste – nie raportuj o koncu pliku
cfg_file >> _val;

this->conf[i].name = _opcja;
this->conf[i].v = _val;
} //foreach file
} // sa rekordy
} //constructor
//——————————————————————–

string config::operator[] (const string _key) {
return this->v(_key);
}
//——————————————————————–

void config::add_tmp_config(string _key, string _v){
if (_key.length()==0) return;
if (_v.length()==0) return;

rec *tmp_conf;
tmp_conf = new rec[(this->conf_ile+1)];

for (unsigned int i=0;iconf_ile;i++) {//foreach file
tmp_conf[i].name = this->conf[i].name;
tmp_conf[i].v = this->conf[i].v;
} //foreach file

tmp_conf[this->conf_ile].name = _key;
tmp_conf[this->conf_ile].v = _v;

delete[] this->conf;

this->conf = tmp_conf;
++this->conf_ile;
}
//——————————————————————–

string config::v(string _key) {
for (unsigned int i=0;iconf_ile;i++) { //foreach file
if (this->conf[i].name == _key) {
return this->conf[i].v;
}
} //foreach file
return “”;
}
//——————————————————————–

config::~config(){
delete[] this->conf;
}
//——————————————————————–
[/php]