MFC reading from a .ini file

Recently I came across a need to read from an .ini file for an MFC application I'm working on. Now some might say why even bother using an .ini file, that's what the registry is for douchebag! Well I need something that a user can easily edit and store 3 small values and creating screens/forms to read/write to the registry doesn't interest me too much. So a simple ini file will do the trick. I found the perfect function is

GetPrivatProfileString

I however ran into some issues using this function. It's a win32 function and I'm using it in an MFC based application with CStrings. The function itself is expecting LPWSTR parameters so I thought by using the CString.GetBuffer method this would work. But I found this eventually will run you out of stack memory and cause exceptions. This even after using the ReleaseBuffer method that MSDN tells us to call after using GetBuffer. So in order to read all the values I needed from the file I found I had to read in LPWSTRs and convert them to CStrings as below. These are all based on a custom class so your mileage may vary. Also there are some issues with USES_CONVERSION in a loop but I'm only doing it once here. I don't like being bound to 4096 characters but I hope nothing in my ini file will ever get that large. If you don't like this solution the next best thing would be to read the .ini file manually and parse it but that is a whole new discussion.

// get the ini file from the string table
m_strIniFile.LoadStringW(IDS_INI_FILE);

LPWSTR load = new WCHAR[4096];
LPWSTR org = new WCHAR[4096];
LPWSTR pos = new WCHAR[4096];

GetPrivateProfileString( _T("scripts"), _T("load"), NULL, load, 4096, m_strIniFile );
GetPrivateProfileString( _T("scripts"), _T("organization"), NULL, org, 4096, m_strIniFile );
GetPrivateProfileString( _T("scripts"), _T("position"), NULL, pos, 4096, m_strIniFile );

// convert LPWSTR to CString
USES_CONVERSION;
m_strLoadSQL = W2CA(load);
m_strOrgSQL = W2CA(org);
m_strPositionSQL = W2CA(pos);

Comments

Jon said…
I know this is a few years old, but here's what you were looking for: http://msdn.microsoft.com/en-us/library/62txabd8%28v=vs.80%29.aspx

Pretty much all of WinAPI exists somewhere in MFC, but made to work better with C++.

Popular posts from this blog

String.Replace vs Regex.Replace

C# Form Application in Kiosk Mode/Fullscreen

C# using a transaction with ODBC