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.GetLe开发者_如何学运维ngth() > 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. :-)
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.
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.
Have you looked at GetPrivateProfileSection? http://msdn.microsoft.com/en-us/library/ms724348(VS.85).aspx
精彩评论