winix/confparser/confparser.cpp

241 lines
3.1 KiB
C++
Executable File

/*
* This file is a part of Winix
* and is not publicly distributed
*
* Copyright (c) 2008-2010, Tomasz Sowa
* All rights reserved.
*
*/
#include "confparser.h"
ConfParser::ConfParser()
{
separator = '=';
commentary = '#';
}
ConfParser::Status ConfParser::Parse(const char * file_name)
{
line = 1;
table.clear();
file.clear();
file.open( file_name );
if( !file )
return cant_open_file;
ReadChar();
status = ParseFile();
file.close();
return status;
}
ConfParser::Status ConfParser::ParseFile()
{
while( lastc != -1 )
{
if( ReadVariable() )
{
if( lastc != separator )
return syntax_error;
ReadChar(); // skipping separator
if( !ReadValue() )
return syntax_error;
//table.insert( std::make_pair(variable, value) );
table[variable] = value;
}
if( lastc == commentary )
SkipLine();
if( lastc != -1 && lastc != '\n' )
return syntax_error;
ReadChar(); // skipping '\n' if was
}
return ok;
}
bool ConfParser::IsVariableChar(int c)
{
if( (c>='a' && c<='z') ||
(c>='A' && c<='Z') ||
(c>='0' && c<='9') ||
c=='.' || c==',' || c=='_' )
return true;
return false;
}
bool ConfParser::IsValueSimpleChar(int c)
{
//if( c==-1 || c=='\n' || IsWhite(c) || c==commentary )
if( c==-1 || c=='\n' || c==commentary )
return false;
return true;
}
bool ConfParser::ReadVariable()
{
variable.clear();
SkipWhite();
while( IsVariableChar(lastc) )
{
variable += lastc;
ReadChar();
}
SkipWhite();
return !variable.empty();
}
bool ConfParser::ReadValue()
{
value.clear();
SkipWhite();
if( lastc == '"' )
// quoted value
return ReadValueQuoted();
else
return ReadValueSimple();
}
bool ConfParser::ReadValueQuoted()
{
ReadChar(); // skipping the first quote
while( lastc != '\n' && lastc != '"' && lastc != -1 )
{
if( lastc == '\\' )
ReadChar();
value += lastc;
ReadChar();
}
if( lastc != '"' )
return false;
ReadChar(); // skipping the last quote
SkipWhite();
return true;
}
bool ConfParser::ReadValueSimple()
{
while( IsValueSimpleChar(lastc) )
{
value += lastc;
ReadChar();
}
Trim(value);
SkipWhite();
return true;
}
int ConfParser::ReadChar()
{
lastc = file.get();
if( lastc == '\n' )
++line;
return lastc;
}
bool ConfParser::IsWhite(int c)
{
if( c==' ' || c=='\t' || c==13 || c==160 )
return true;
return false;
}
void ConfParser::SkipWhite()
{
while( IsWhite(lastc) )
ReadChar();
}
void ConfParser::SkipLine()
{
while( lastc != -1 && lastc != '\n' )
ReadChar();
}
void ConfParser::Trim(std::string & s)
{
std::string::size_type i;
if( s.empty() )
return;
// looking for white characters at the end
for(i=s.size()-1 ; i>0 && IsWhite(s[i]) ; --i);
if( i==0 && IsWhite(s[i]) )
{
// the whole string has white characters
s.clear();
return;
}
// deleting white characters at the end
if( i != s.size() - 1 )
s.erase(i+1, std::string::npos);
// looking for white characters at the beginning
for(i=0 ; i<s.size() && IsWhite(s[i]) ; ++i);
// deleting white characters at the beginning
if( i != 0 )
s.erase(0, i);
}