pppc/Config.cc
joshholtrop 3c22f00c7d fleshing out Config::read() more
git-svn-id: http://apu.dw.local/svnusers/JoshHoltrop/pppc/trunk@53 8131a0b2-b21c-1c47-bd6a-f003126495bd
2009-08-19 17:41:22 +00:00

123 lines
3.3 KiB
C++

#include "Config.h"
#include "trim.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
Config::Entry::Entry(const string & name)
{
this->name = name;
pin = -1;
on_start = NONE;
on_exit = NONE;
on_lock = NONE;
on_unlock = NONE;
}
Config::Config()
{
port = "LPT1"; /* default to first parallel port */
}
void Config::read(const char * file)
{
ifstream ifs(file);
if (ifs.is_open())
{
int entry_num = -1;
string line;
while (!ifs.eof())
{
getline(ifs, line);
line = trim(line);
if (line == "") /* skip blank lines */
continue;
if (line[0] == ';' || line[0] == '#') /* skip comments */
continue;
/* Look for the beginning of a new entry section */
if (line[0] == '[' && line[line.size()-1] == ']')
{
entries.push_back(Entry(string(line, 1, line.size() - 2)));
entry_num++;
continue;
}
/* split the line into variable and value parts */
pair<string, string> parts = split(line);
if (entry_num == -1)
{
if (parts.first == "port")
{
if (parts.second != "")
port = parts.second;
}
else
{
cerr << "Warning: Unrecognized global command: "
<< line << endl;
}
}
else
{
if (parts.first == "on_start")
{
entries[entry_num].on_start = parseAction(parts.second);
}
else if (parts.first == "on_exit")
{
entries[entry_num].on_exit = parseAction(parts.second);
}
else if (parts.first == "on_lock")
{
entries[entry_num].on_lock = parseAction(parts.second);
}
else if (parts.first == "on_unlock")
{
entries[entry_num].on_unlock = parseAction(parts.second);
}
else
{
cerr << "Warning: Unrecognized entry command: "
<< line << endl;
}
}
}
}
else
{
cerr << "Warning: Could not open '" << file << "'" << endl;
}
}
pair<string, string> Config::split(const string & line)
{
pair<string, string> res;
size_t pos = line.find('=');
if (pos != string::npos)
{
res.first = trim(string(line, 0, pos));
res.second = trim(string(line, pos + 1, line.size() - pos - 1));
}
return res;
}
Config::Action Config::parseAction(const string & str)
{
string s = str;
Action res = NONE;
for (int sz = s.size(), i = 0; i < sz; i++)
s[i] = tolower(s[i]);
if (s == "on")
res = ON;
else if (s == "off")
res = OFF;
else if (s == "previous")
res = PREVIOUS;
return res;
}