I have written a CFG (text file) parser for my specific needs. I have found other libraries to be much too large. Even other parsers that bill themselves as "simple" run hundreds of line long.
The code that I need reviewed is the parsing and tokenizing of the input. I feel like it can be simplified. I have added more comments than required just to make it easier for you guys to read.
Here are member variables used in the class:
std::string m_cfgFilename;
std::map<std::string, std::string> m_cfgMap;
std::stringstream m_buffer;
The initialization:
bool CFG::Init(std::string filename)
{
// Save the filename for the reload
m_cfgFilename = filename;
if(filename.empty())
{
return false;
}
std::ifstream t(filename);
if (!t.is_open())
return false;
m_buffer << t.rdbuf();
Parse();
return true;
}
The parsing:
void CFG::Parse()
{
std::string line;
std::istringstream s(m_buffer.str());
std::string commentKey("#");
while (std::getline(s, line))
{
// Ignore empty and comment lines
if (!line.empty() && line.compare(0, commentKey.length(), commentKey))
{
// Split the line
std::vector<std::string> seglist;
std::string segment;
std::istringstream ss(line);
while (std::getline(ss, segment, '='))
{
// Trim the white space
std::stringstream trimmer;
trimmer << segment;
segment.clear();
trimmer >> segment;
std::transform(segment.begin(), segment.end(), segment.begin(), ::tolower);
seglist.push_back(segment);
}
// Only
if (seglist.size() == 2)
{
m_cfgMap[seglist[0]] = seglist[1];
}
}
}
}
I am curious if there is a way to cut down on all the different strings and stream conversions.
Here is a sample cfg I would throw at it:
# Test CFG File
# General
name = alfred
numPopsicles = 12
height = 14.5
loadCharacters = true
I should also mention that it does work perfectly. Just worried about redundant code.