fleshing out Config::read() more

git-svn-id: http://apu.dw.local/svnusers/JoshHoltrop/pppc/trunk@53 8131a0b2-b21c-1c47-bd6a-f003126495bd
This commit is contained in:
joshholtrop 2009-08-19 17:41:22 +00:00
parent 874021f94f
commit 3c22f00c7d
2 changed files with 95 additions and 0 deletions

View File

@ -1,5 +1,6 @@
#include "Config.h"
#include "trim.h"
#include <iostream>
#include <fstream>
#include <string>
@ -15,15 +16,76 @@ Config::Entry::Entry(const string & name)
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
@ -31,3 +93,30 @@ void Config::read(const char * file)
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;
}

View File

@ -4,6 +4,7 @@
#include <string>
#include <vector>
#include <utility> /* pair */
class Config
{
@ -26,7 +27,12 @@ class Config
std::string port;
std::vector<Entry> entries;
Config();
void read(const char * file);
protected:
std::pair<std::string, std::string> split(const std::string & line);
Action parseAction(const std::string & str);
};
#endif