帮助改进这个INI解析代码
这是我针对这个问题< /a>. 我对此并不完全满意,我认为这是一个帮助改进我对 STL 和基于流的编程的使用的机会。
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 文件中解析一些配置字符串。
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;
}
}
}
}
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我会使用 boost::regex 来匹配每种不同类型的元素,例如:
正则表达式可能需要一些调整。
我还将 de stream.getline 替换为 std::getline,从而摆脱静态 char 数组。
I would use boost::regex to match for every different type of element, something like:
the regular expressions might need some tweaking.
I would also replace de stream.getline with std::getline, getting rid of the static char array.
这:
应该通过调用 wstrchr、wcschr、WSTRCHR 或其他东西来简化,具体取决于您所在的平台。
This:
should be simplified by a call to wstrchr, wcschr, WSTRCHR, or something else, depending on what platform you are on.
使用标准字符串标头中的(非成员)getline 函数。
Use the (nonmember) getline function from the standard string header.