::GetPrivateProfileString read whole section of INI file

♀尐吖头ヾ 提交于 2019-12-23 11:58:48

问题


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. :-)


回答1:


You don't need to read the file manually but it helps to read the manual for GetPrivateProfileString:

lpKeyName [in] : The name of the key whose associated string is to be retrieved. If this parameter is NULL, all key names in the section specified by the lpAppName parameter are copied to the buffer specified by the lpReturnedString parameter.




回答2:


You should probably consider the use of Boost.PropertyTree (which provides a INI parser) :

The Property Tree library provides a data structure that stores an arbitrarily deeply nested tree of values, indexed at each level by some key. Each node of the tree stores its own value, plus an ordered list of its subnodes and their keys. The tree allows easy access to any of its nodes by means of a path, which is a concatenation of multiple keys.

In addition, the library provides parsers and generators for a number of data formats that can be represented by such a tree, including XML, INI, and JSON.




回答3:


Have you looked at GetPrivateProfileSection? http://msdn.microsoft.com/en-us/library/ms724348(VS.85).aspx



来源:https://stackoverflow.com/questions/4534048/getprivateprofilestring-read-whole-section-of-ini-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!