帮助改善此INI解析代码 [英] Help improve this INI parsing code
问题描述
这是我为创建的简单内容这个问题.我对此并不完全满意,我将其视为改善我对STL和基于流的编程的使用的机会.
This is something simple I came up with for this question. I'm not entirely happy with it and I saw it as a chance to help improve my use of STL and streams based programming.
std::wifstream file(L"\\Windows\\myini.ini");
if (file)
{
bool section=false;
while (!file.eof())
{
std::wstring line;
std::getline(file, line);
if (line.empty()) continue;
switch (line[0])
{
// new header
case L'[':
{
std::wstring header;
size_t pos=line.find(L']');
if (pos!=std::wstring::npos)
{
header=line.substr(1, pos);
if (header==L"Section")
section=true;
else
section=false;
}
}
break;
// comments
case ';':
case ' ':
case '#':
break;
// var=value
default:
{
if (!section) continue;
// what if the name = value does not have white space?
// what if the value is enclosed in quotes?
std::wstring name, dummy, value;
lineStm >> name >> dummy;
ws(lineStm);
WCHAR _value[256];
lineStm.getline(_value, ELEMENTS(_value));
value=_value;
}
}
}
}
您将如何改善呢?请不要推荐其他库-我只想要一种简单的方法来从INI文件中解析出一些配置字符串.
How would you improve this? Please do not recommend alternative libraries - I just want a simple method for parsing out some config strings from an INI file.
推荐答案
//如果name = value没有空格怎么办?
//如果值用引号引起来怎么办?
// what if the name = value does not have white space?
// what if the value is enclosed in quotes?
我将使用boost :: regex来匹配每种不同类型的元素,例如:
I would use boost::regex to match for every different type of element, something like:
boost::smatch matches;
boost::regex name_value("(\S+)\s*=\s*(\S+)");
if(boost::regex_match(line, matches, name_value))
{
name = matches[1];
value = matches[2];
}
正则表达式可能需要进行一些调整.
the regular expressions might need some tweaking.
我还将用std :: getline替换de stream.getline,摆脱静态char数组.
I would also replace de stream.getline with std::getline, getting rid of the static char array.
这篇关于帮助改善此INI解析代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!