Date: 2008may27
Platform: win32
Q. How do I read a section of an .ini file?
A. This code shows how to do just that.
#include <map>
// Helper
inline int FileSize(LPCSTR file)
{
struct stat sb;
if (stat(file, &sb) < 0) return -1;
return sb.st_size;
}
// This is where the section will go
typedef std::map<CString, CString> SECT;
static BOOL GetSection(LPCSTR szFile, LPCSTR szSection, SECT §ion)
{
int size;
LPSTR pBuf;
LPSTR p, q, next, val;
section.clear();
// Allocate a buffer as big as the .ini file
if ((size = filesize(szFile)) < 0) return FALSE;
if ((pBuf = (LPSTR)malloc(size)) == NULL) return FALSE;
// Read the section into memory
GetPrivateProfileSection(szSection, pBuf, size, szFile);
for (p = pBuf; *p; p = next)
{
next = p + lstrlen(p) + 1;
if ((q = strchr(p, '=')) == NULL)
{
q = p + lstrlen(p);
val = q;
}
else
{
val = q + 1;
}
*q = '\0';
section[p] = val;
}
free(pBuf);
return TRUE;
}
// Example use
main()
{
LPCSTR szFile = "c:/temporary/myfile.ini";
LPCSTR szSection = "stuff";
SECT sect;
GetSection(szFile, szSection, sect);
for (SECT::iterator it = sect.begin(); it != sect.end(); it++)
{
printf("[%s]=[%s]\n", it->first, it->second);
}
}
| What this info useful to you? You can donate to say thanks |
Add a comment
Sign in to add a comment