::GetPrivateProfileString 读取 INI 文件的整个部分
我正在修改现有的 C++ 应用程序并移出一些当前硬编码的值。
我正在使用一个类来执行此操作,该类将“管理”整个事情并保存 INI 文件中的值的 map
。
现在我必须使用 ::GetPrivateProfileString
函数单独读取每个值 - 我可以以某种方式读取整个部分而不是单个值吗?
不想手动读取文件,但如果有任何合理(即高效+易于使用)的现有方式,我愿意寻求建议。
编辑:刚才必须“真正”使用它,解决方案确实是将 NULL 作为 lpKeyName 值传递。包括解析返回值的完整代码:
char buffer[MAX_STRING_SIZE];
int charsCount = ::GetPrivateProfileString("MySection", NULL, NULL, buffer, MAX_STRING_SIZE, m_strIniPath);
CString curValue;
curValue.Empty();
char curChar = '\0';
for (int i = 0; i < charsCount; i++)
{
curChar = buffer[i];
if (curChar == '\0')
{
if (curValue.GetLength() > 0)
HandleValue(curValue);
curValue.Empty();
}
else
{
curValue.AppendFormat("%c", curChar);
}
}
if (curValue.GetLength() > 0)
HandleValue(curValue);
这并不简单,因为它返回由零字符(EOS?)分隔的键,因此我必须使用如上所述的循环来提取它们 - 为了每个可能需要它的人而在此处共享它。 :-)
I'm modifying existing C++ application and moving out some values that are currently hard coded.
I'm doing this with one class that will "manage" this whole thing and hold map<CString, CString>
of the values from the INI file.
Right now I have to read each value separately using ::GetPrivateProfileString
function - can I somehow read whole section instead of single value?
Prefer not to have to read the file manually, but if there's any reasonable (i.e. efficient + simple to use) existing way I'm open for suggestions.
Edit: just now had to use it "for real" and the solution was indeed passing NULL as the lpKeyName value. Complete code including parsing the return value:
char buffer[MAX_STRING_SIZE];
int charsCount = ::GetPrivateProfileString("MySection", NULL, NULL, buffer, MAX_STRING_SIZE, m_strIniPath);
CString curValue;
curValue.Empty();
char curChar = '\0';
for (int i = 0; i < charsCount; i++)
{
curChar = buffer[i];
if (curChar == '\0')
{
if (curValue.GetLength() > 0)
HandleValue(curValue);
curValue.Empty();
}
else
{
curValue.AppendFormat("%c", curChar);
}
}
if (curValue.GetLength() > 0)
HandleValue(curValue);
It's not trivial as it returns the keys separated by zero character (EOS?) so I had to extract them using loop such as the above - share it here for the sake of everyone who might need it. :-)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不需要手动阅读该文件,但阅读
You don't need to read the file manually but it helps to read the manual for GetPrivateProfileString:
您可能应该考虑使用 Boost.PropertyTree (它提供了 INI 解析器):
You should probably consider the use of Boost.PropertyTree (which provides a INI parser) :
您看过 GetPrivateProfileSection 吗? http://msdn.microsoft.com/en-us/库/ms724348(VS.85).aspx
Have you looked at GetPrivateProfileSection? http://msdn.microsoft.com/en-us/library/ms724348(VS.85).aspx