Skip to content

Instantly share code, notes, and snippets.

@aggieben
Created June 10, 2009 13:06
Show Gist options
  • Save aggieben/127194 to your computer and use it in GitHub Desktop.
Save aggieben/127194 to your computer and use it in GitHub Desktop.
#include <istream>
#include <stdexcept>
#include <string>
#include <sstream>
#include "text_config.hpp"
namespace {
std::string get_section_name(std::string& line)
{
std::string::size_type pos_beg;
std::string::size_type pos_end;
posBeg = line.find_first_not_of(' ', 1); // should be begin of section name
posEnd = line.find_last_not_of(" ]"); // should be end of section name
if (std::string::npos == line.find(']'))
{
std::stringstream ss;
ss << "parse error (" << pos_end+1 << "): " << line;
throw std::runtime_error(ss.str());
}
return line.substr(pos_beg, pos_end-pos_beg+1);
}
}
std::istream& operator>>(std::istream& in, text_config& conf)
{
std::string line;
std::string section;
std::string val;
std::string key;
while (in)
{
std::getline(in, line);
if (line == "")
{
if (val != "")
{
conf[section][key] = val;
val.clear();
key.clear();
}
continue;
}
switch (line[0]) // then we're done with this section
{
case '[':
section = get_section_name(line);
break;
case ' ': // this line must have other text on it, so append
// to the previous line
val += line;
break;
default: // key-value pair
if (val != "")
{
conf[section][key] = val;
val.clear();
key.clear();
}
std::string::size_type sep_pos = line.find(':');
std::string::size_type key_end = line.substr(0, sep_pos).find_last_not_of(' ');
key = line.substr(0, key_end+1);
std::string::size_type val_beg = line.find_first_not_of(' ', sep_pos+1);
std::string::size_type val_end = line.find_last_not_of(' ');
val = line.substr(val_beg, val_end-val_beg+1);
};
}
}
std::ostream& operator<<(std::ostream& out, text_config& conf)
{
for (text_config::iterator itr = conf.begin(); itr != conf.end(); ++itr)
{
out << "[ " << itr->first << " ]\n";
for (text_config::mapped_type::iterator jtr = itr->second.begin();
jtr != itr->second.end(); ++jtr)
{
out << jtr->first << " = " << jtr->second << "\n";
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment