Twelve lines C++ INI parser

TL;DR

std::map<std::string, std::map<std::string,std::string>> data; 
std::string group;
for(const auto &line: underscore::file(inifile)){
 auto l=line.split('#',true)[0];
 if (l.empty())  continue;
 if (l.startswith("[") && l.endswith("]")) 
  group=l.slice(1,-2);
 else{
  auto p=l.split('=',true);
  data[group][p[0].strip()]=l.slice(p[0].length()+1,-1).strip();
 } 
}

The power of underscore.hpp

With the use of underscore.hpp I was able to do a fairly simple, inefficient, and perfect for this place parser for ini files in just 12 lines. Its for sure less efficient that a hand crafted parser, as it reads a lot of data in memory and the starts slicing it out, and there is no error checking. But for simple ini files, it just works.

The idea is to parse just line by line (line 3), then slice out comments and empty lines (lines 4 and 5). Then we check if we are inside a group (startswith, endswith, line 6), and if so keep the group name. If not, then split at =, and keep on the key name the first part, and the rest (careful, that’s not l[1], but from = on), is the value.

As a result we have a nice map of strings to map of strings to string, that is just data[group][key]=value. For parts without group, the group name is “”. If there is something that is not a group nor a key=value line, then it will just store all line as the key.

Over all this we need not accessing methods, list all keys methods and so on. All of it can be accessed at garlic source code.

Leave a Reply