Click here to Skip to main content
12,829,316 members (43,773 online)
Click here to Skip to main content
Add your own
alternative version


40 bookmarked
Posted 24 Nov 2006

A Simple Class to Read and Write INI Files

, 30 Nov 2006 CPOL
Rate this:
Please Sign up or sign in to vote.
This class is a thin MFC wrapper around Win32 API for reading/writing INI files.


This is a further exploration if the INI file class theme started by Xiangxiong Jian (xiaohe521) and Adam (aejw) on The Code Project. The main idea remains pretty much the same: the class is a thin wrapper around Win32 <stockticker />API</stockticker /> for reading/writing INI files. However, I was trying to gear my class more towards the <stockticker />MFC</stockticker />.

This class may be useful if your application needs to access both registry and INI file, or multiple INI files. Otherwise, you could use AfxGetApp()->m_pszProfileName and AfxGetApp()->GetProfileXXXX(…).

Class Declaration

class CIniFile : public CObject
 CIniFile(LPCTSTR lpIniFileName, INT iMaxStringLength);
 virtual ~CIniFile();
// Attributes
 CString  m_strFileName; 	// path to the INI file
 const INT m_MAXSTRLEN; 	// max length of a string (excluding the key name)
                        	//that can be written/read to/from the
                        	// INI file by this instance
// Operations
 CString GetIniFileName();
 void SetIniFileName(LPCTSTR lpIniFileName);
 BOOL GetStatus(CFileStatus& rStatus);
void GetString(LPCTSTR lpSection, LPCTSTR lpKey,
       CString& strRet, LPCTSTR strDefault);
UINT GetInt(LPCTSTR lpSection, LPCTSTR lpKey, INT iDefaultValue);
FLOAT GetFloat(LPCTSTR lpSection, LPCTSTR lpKey, FLOAT fDefaultValue);
BOOL GetStruct(LPCTSTR lpSection, LPCTSTR lpKey,
       LPVOID lpRetStruct, UINT iSizeStruct);
void GetSectionNames(CStringList& lstSectionNames);
BOOL WriteSection(LPCTSTR lpSection, LPCTSTR lpData);
BOOL WriteString(LPCTSTR lpSection, LPCTSTR lpKey, LPCTSTR lpString);
BOOL WriteNumber(LPCTSTR lpSection, LPCTSTR lpKey, INT iValue);
BOOL WriteNumber(LPCTSTR lpSection, LPCTSTR lpKey, FLOAT fValue);
BOOL WriteStruct(LPCTSTR lpSection, LPCTSTR lpKey,
       LPVOID lpStruct, UINT iSizeStruct);
 BOOL RemoveKey(LPCTSTR lpSection, LPCTSTR lpKey); 

Class Implementation

The implementation is very straightforward. It’s based on the following <stockticker />API</stockticker /> functions:

  • GetPrivateProfileSectionNames
  • GetPrivateProfileStruct
  • GetPrivateProfileString
  • GetPrivateProfileInt
  • WritePrivateProfileStruct
  • WritePrivateProfileString
  • WritePrivateProfileSection

Download the source code for details (it's fairly well commented).

Demo Application / Test Bed

Here’s the console application that exercises the methods of the class. The output goes to the afxDump.

// just a dummy structure to write/read to/from the INI file
struct TestStruct : public POINT
 char charr[8];
// PURPOSE: test bed for the INI file class
void TestIniClass()
 CIniFile iniFile(".\\test1.ini", 1024);
 iniFile.SetIniFileName(".\\test2.ini");     		// change the file name 
					 // after the class has bee created
// test the writing to the INI file
iniFile.WriteSection("section1", "key1=test1\x000key2=test2"); // make a section
                           // with 2 new keys
iniFile.WriteSection("section2", "key1=test1");    // make another section
iniFile.WriteString("section1", "key3", "test3");      // create a new key
iniFile.WriteString("section1", "key2", "test4");      // update an existing key
iniFile.WriteString("section1", "key1", NULL);     // remove an existing key
iniFile.RemoveKey("section1", "key3");             // remove another existing key
iniFile.WriteNumber("section1", "key4", 123);      // write an integer
                       // to a new key
iniFile.WriteNumber("section1", "key5", -123);     // write a negative integer
                       // to a new key
iniFile.WriteNumber("section1", "key6", -123.456f);    // write a float to a new key
TestStruct writeTestStruct;
writeTestStruct.x = 6;
writeTestStruct.y = 7;
strcpy(writeTestStruct.charr, "abcdefg");
iniFile.WriteStruct("section1", "key7", &writeTestStruct, sizeof(TestStruct));

// Test the reading from the INI file
CString str;           // string that will receive the output
iniFile.GetString("section1", "key2", str, "default"); TRACE("key2=%s\n", str);
iniFile.GetString("section1", "nokey", str, "default");
   TRACE("nokey=%s\n", str); // non-existent key
iniFile.GetString("section3", "key1", str, "default"); TRACE("nokey=%s\n", str);
TRACE("key4=%d\n", iniFile.GetInt("section1", "key4", 0));
TRACE("key5=%d\n", iniFile.GetInt("section1", "key5", 0));
TRACE("key6=%f\n", iniFile.GetFloat("section1", "key6", 0));
TestStruct readTestStruct;
iniFile.GetStruct("section1", "key7", &readTestStruct, sizeof(TestStruct));
TRACE("key7= %ld %ld %s\n", readTestStruct.x,
   readTestStruct.y, readTestStruct.charr);
 // Test the section list retrieval
 CStringList lstSectionNames;
 for (POSITION pos = lstSectionNames.GetHeadPosition(); pos != NULL; )
  TRACE("\t%s\n", lstSectionNames.GetNext(pos));

Is there anything that should be fixed, added or removed in this project? Please let me know!


[1] A Small Class to Read INI File

[2] INI Class for .NET

[3] CIni

Revision History

Rev 0.1Initial draftNick AlexeevNov 24, 2006
Rev 0.2Added exception handlingNick AlexeevNov 30, 2006


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Nick Alexeev
Systems Engineer Prolitech
United States United States
doing business as Prolitech
Redwood City, CA

blog (mostly technical)

You may also be interested in...


Comments and Discussions

QuestionErrors in VS2010 Pin
Tarun2221-May-12 22:47
memberTarun2221-May-12 22:47 
GeneralGetPrivateProfileString() in XP and Vista Pin
Roger Gonsalves6-Sep-09 17:51
memberRoger Gonsalves6-Sep-09 17:51 
Questionhow to Pin
pbturner9-May-07 6:38
memberpbturner9-May-07 6:38 
GeneralRe: how to [modified] Pin
Nick Alexeev9-May-07 8:15
memberNick Alexeev9-May-07 8:15 
GeneralRe: how to Pin
pbturner9-May-07 9:03
memberpbturner9-May-07 9:03 
Hi Nick,

i wouldn't be in this thing (VC++ 2005) either if it weren't for the fact we've got a vendor developing a product for us and that's what they're using. our company is currently using Borland C++ (6.0 and 2006), but many of us have MS V Studio experience (older versions). i'm one of the first in this new environment, as i'm probably going to be the one to take over support of this "new product".

i have an application (created in Borland C++ Builder 6.0) that reads from an INI file and displays the info in a listbox. from there, the user selects one of the items in the list box, and then some items in a group of check boxes. pretty simple. figured it wouldn't be that hard to re-create in VC++ 2005.

anyway, what i did, was to create a new "Windows Forms Application" type of application, as that appeared to be the best choice of the "installed templates". my other choices were "Class Library", "CLR Empty Project", "CLR Console Application", and the one I chose. from there, it automatically makes choices/settings for you. looking at the project options, it has MFC and ATL support.

created a screen with some objects, buttons, widgets, etc. all is good so far. now for the fun part. want to try and read the values from the INI file, like before, but have been having a real hard time with what used to be a very simple type of operation (strings, ini files, etc.). came across a comment in another support group that indicated that VC++ 2005 was like starting over in programming 101. the confusion, i'm sure, has to do with the complete changeover to managed classes (?) and the more strict environment.

Tried simply including the IniFile.cpp into the project and that's where it went south. by my thinking, having the MFC defined in the project settings, should have made the CObject definition available. again, i'm assuming that most of this is due to my inexperience with the VC++ 2005 environment.

Thanks for any support/comments/help you can provide.

pbt. (Pete).
GeneralThanks Pin
jfrancis21-Dec-06 14:52
memberjfrancis21-Dec-06 14:52 
GeneralRe: Thanks Pin
Nick Alexeev28-Jan-07 8:36
memberNick Alexeev28-Jan-07 8:36 
GeneralRe: Thanks Pin
nickhalfasleep24-Apr-07 11:20
membernickhalfasleep24-Apr-07 11:20 
QuestionHow many more do we need? Pin
Mark Nischalke25-Nov-06 3:54
memberMark Nischalke25-Nov-06 3:54 
AnswerRe: How many more do we need? Pin
Sceptic Mole26-Nov-06 2:00
memberSceptic Mole26-Nov-06 2:00 
AnswerRe: How many more do we need? Pin
CPallini30-Nov-06 22:21
memberCPallini30-Nov-06 22:21 
AnswerRe: How many more do we need? Pin
Abu Mami1-Dec-06 2:27
memberAbu Mami1-Dec-06 2:27 
AnswerRe: How many more do we need? Pin
Stephen Hewitt5-Dec-06 13:30
memberStephen Hewitt5-Dec-06 13:30 
GeneralRe: How many more do we need? Pin
Nick Alexeev5-Dec-06 21:17
memberNick Alexeev5-Dec-06 21:17 
GeneralA suggestion. Pin
cpallini25-Nov-06 1:57
membercpallini25-Nov-06 1:57 
GeneralRe: A suggestion. Pin
Nick Alexeev25-Nov-06 17:00
memberNick Alexeev25-Nov-06 17:00 
GeneralRe: A suggestion. Pin
cpallini25-Nov-06 23:06
membercpallini25-Nov-06 23:06 
GeneralRe: A suggestion. Pin
Nick Alexeev30-Nov-06 21:05
memberNick Alexeev30-Nov-06 21:05 
GeneralRe: A suggestion. Pin
CPallini30-Nov-06 22:20
memberCPallini30-Nov-06 22:20 
QuestionOrigional? Pin
WalderMort24-Nov-06 18:29
memberWalderMort24-Nov-06 18:29 
AnswerRe: Origional? [modified] Pin
Nick Alexeev24-Nov-06 18:43
memberNick Alexeev24-Nov-06 18:43 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170326.1 | Last Updated 1 Dec 2006
Article Copyright 2006 by Nick Alexeev
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid