Working with INI Configuration Files Cross-Platform (Win32/Un*x, MBCS/Unicode)

SimpleIni

Cross platform programming can be painful, especially when it comes to simple tasks that you don't want to think about because they aren't your main problem. Unfortunately, it sometimes takes longer than it should to solve these tasks. One of these problems is loading configuration files. Although cross-platform XML libraries are available, if the user of your software is going to directly modify the file, it can be painful. The old Windows INI configuration file is a lasting file format that is easy for the user to understand and hard to get wrong.

This component is a C++ class that provides the ability to load an INI-style configuration file on both Windows and Linux/Unix. It is fast, simple, and source code using this component will compile unchanged on either OS. It supports both MBCS and Unicode builds on Windows, and can load UTF-8 or MBCS files on all platforms.

Features

  • Public domain, free use in all software (including GPL and commercial)
  • Multi-platform (Windows 95/98/ME/NT/2K/XP/2003, Linux, Unix)
  • Loads and saves INI-style configuration files
  • Liberal acceptance of file format
    • Key/Values with no section
    • Removal of whitespace around sections, keys, and values
  • Optional case-insensitive sections and keys (for ASCII characters only)
  • Supports both char or wchar_t programming interfaces
  • Supports both MBCS (system locale) and UTF-8 file encodings
  • System locale does not need to be UTF-8 on Linux/Unix to load UTF-8 file
  • Support for non-ASCII characters in section, keys, values, and comments
  • Support for non-standard character types or file encodings via user-written converter classes
  • Support for adding/modifying values programmatically

Usage Summary

  1. Declare an instance of the appropriate class. Note that the following definitions are just shortcuts for commonly used types. Other types (for example, PRUnichar, unsigned short, unsigned char) are also possible.
  2. Interface Case-sensitive Typedef
    char No CSimpleIniA
    char Yes CSimpleIniCaseA
    wchar_t No CSimpleIniW
    wchar_t Yes CSimpleIniCaseW
  3. Call LoadFile() to load and parse the INI configuration file.
  4. Use the following functions to access the file's data:
  5. GetAllSections Return all section names
    GetAllKeys Return all key names for a section
    GetSection Return all key names and values in a section
    GetSectionSize Return the number of keys in a section
    GetValue Return a value for a section & key
    SetValue Add or update a value for a section & key
  6. Call SaveFile() to save the INI configuration file (if necessary)

Notes

  • The collation (sorting) order used for sections and keys returned from iterators is NOT DEFINED. If collation order of the text is important, you should do it yourself by either supplying a replacement SI_STRCMP class or by sorting the strings external to this library.
  • Linux/Unix systems must also compile and link ConvertUTF.c.
  • To load a UTF-8 file on Windows and expose it with SI_CHAR == char, you need to define SI_USING_WIN32_CHAR_FOR_UTF8.

Download

The current version of SimpleIni is 1.5. The home page is http://code.jellycan.com/SimpleIni/.

Example Program

This program loads an INI file and dumps out all of the data from it.

#include "SimpleIni.h"

int main(int argc, char * argv[])
{
   setlocale(LC_CTYPE, "");

   if (argc < 2) {
      printf(
         "Usage: %s iniFile [useMBCS]\n"
         "   Pass 1 for useMBCS to use system locale file
             encoding\n",
         argv[0]);
      return 1;
   }
   bool bIsUtf8 = (argc < 3) ? true : *argv[2] != '1';

   const char * pDebug;
   printf("Dumping file using char version:\n");
   CSimpleIniA ini;
   if (0 != ini.LoadFile(argv[1], bIsUtf8)) {
      printf("Failed to open: %s\n", argv[1]);
       exit(1);
   }
   CSimpleIniA::TNames sections;
   ini.GetAllSections(sections);
   CSimpleIniA::TNames::const_iterator j = sections.begin();
   for ( ; j != sections.end(); ++j ) {
      printf("\n");
      if (*j[0]) {
         printf("[%s]\n", pDebug = *j);
      }
      const CSimpleIniA::TKeyVal * pSection = ini.GetSection(*j);
      if (pSection) {
         CSimpleIniA::TKeyVal::const_iterator i =
            pSection->begin();
         for ( ;i != pSection->end(); ++i) {
            printf("%s=%s\n", pDebug = i->first, i->second);
         }
      }
   }

   printf("\nQuerying section: [standard]\n");
   CSimpleIniA::TNames keys;
   ini.GetAllKeys("standard", keys);
   CSimpleIniA::TNames::const_iterator k = keys.begin();
   for ( ; k != keys.end(); ++k ) {
      printf("Key: %s\n", pDebug = *k);
   }

   pDebug = ini.GetValue("standard", "foo", 0);
   printf("\nValue of standard::foo is '%s'\n", pDebug ?
           pDebug : "(null)");

   ini.SetValue("standard", "foo", "wibble");
   pDebug = ini.GetValue("standard", "foo", 0);
   printf("Value of standard::foo is now '%s'\n", pDebug ?
           pDebug : "(null)");

   FILE * fp = fopen("testsi-char.ini", "wb");
   if (fp) {
      ini.SaveFile( fp, "; testsi.cpp test output (char)" SI_NEWLINE );
      fclose(fp);
   }

   return 0;
}

Disclaimer

This code is released as public domain. You can do with it whatever you like: use it, modify it, distribute it, sell it, delete it, or send it to your mother-in-law. I make no promises or guarantees that this code will work correctly or at all. Use it completely at your own risk.



About the Author

Brodie Thiesfield

Programming to eat. Donations of canned food accepted.

Downloads

Comments

  • http://www.tomsoutletw.com/ cfdtno

    Posted by http://www.tomsoutletw.com/ Mandyiov on 03/31/2013 01:47am

    Luo Bi heart today to thoroughly understand what is called lurking around, even if that white tiger has occupied the pig was, still alert and discontent looked Luo Bi heart and Qi Zhen Yu appears in the estimate cheap ray ban sunglasses own claws under the pork there how much threat coefficient even if it does not mind immediately live tear ray ban wayfarer two, that eyes let Luo Bi heart shudder, I just feel the wrist Qi Zhen Yu Meng pulled covered Jiling quickly scratching and scrambling stand up, the speed of light flash to the side to highlight ray ban wayfarer sizes not covet meaning of Tiger uncle to supper.ray ban clubmaster, Everyone a retreat passed, until no retreat, sent did not jump off the career to go to the body Mingzhi, that the white tiger was recovered coercion eyes, fiddled with the horse slowly with his tigers corpse inside the pig child all unfolds.oakley sunglasses, Although Luo Bi heart can not see it at this time to gaze, but she felt that they reveal should feel quite satisfied, is difficult to give it a good mood uncle ...... really put everyone a chance to live, my heart can not help but ignite the fire of a fragment of hope.

    Reply
  • http://www.nikeairmaxwr.com/ vggkpw

    Posted by http://www.nikeairmaxwr.com/ Suttonnau on 03/28/2013 07:01am

    ray ban wayfarer,Gang hand saw in a pub drinking Taitailielie not care about her human weapon has been exposed in the eyes of the next to a public pervert uncle, so he took a bottle of wine to go out into that rosy sexy lips irrigation that bold gesture people see excitedly heart. But only the heart only, the countless examples try to manually tell discount oakley sunglasses, the immediate stunner dreadful existence, the light beating lying at home for a few months, severe beat missing limbs; most can afraid and magic is her beat, oakley sunglasses sale not even a drop of blood, but it will be hit covered the swollen even his mother does not recognize, it is tragic ah!ray ban, Her pervert uncle who is only a distance, but not nearly ditch the Wild Rose.cheap ray ban sunglasses, Look at her mute dejected listless look, you know Tsunade just the money in, come here Jiejiuxiaochou.

    Reply
  • cheap ugg boots oEgjjTou http://www.cheapfashionshoesan.com/

    Posted by Mandyqaj on 03/11/2013 02:31am

    hollister sbxbczdi hollister uk wqoapxjd hollister outlet uk mzdlhksz hollister sale caisykpy hollister uk sale yjqmkvtw hollister sale uk szovtxfl cheap hollister pccsmewt hollister outlet xgqgexzq hollister london pfblfgqi

    Reply
  • cheap ugg boots zDoe gWnb

    Posted by Mandyqez on 03/09/2013 01:55pm

    ugg wqqusxse botas ugg ssoohatj ugg españa

    Reply
  • ghd australia qrdpip

    Posted by Suttonzns on 03/09/2013 06:17am

    Cheap Timberland Boots jwzluzud Timberland Outlet fzaagfuz Timberland Boots Cheap cneliywc Timberland Boots iqkuamya

    Reply
  • ghd australia nrtuyv

    Posted by Suttoneoh on 02/07/2013 01:43pm

    4vAuh christian louboutin jZmp longchamp outlet pYro michael kors outlet 4mAat 0tPxe chi 9vWgd michael kors outlet 3hXry cheap nfl jerseys 1wIzi nike uk 5zDvy ghd 7hAit ugg 2xXdc toms outlet 2aUvi Tory Burch Leather Wheat Wedge Cheap 7kYzl hollister lyon 9zKlh ghd 0hVyd ugg boots sale

    Reply
  • cheap ugg boots eTlc iDen

    Posted by Suttongnl on 02/05/2013 04:42am

    gHih louboutin femme mHio longchamp bags lXlw michael kors bags 1uGrc 6cGll chi hair straightener 7nIpx michael kors outlet 1mFym cheap New Orleans Saints Heart Soul Light grey T-Shirt 8vHmf nike uk 3dHfc ghd 8eNgs ugg 6sPtj toms shoes 1dRkb Tory Burch Snake Print Pink Wallets CheapNewest Tory Burch Zip Purple Wallets CheapTory Burch Mini Sling Shoulder Bags Orange CheapTory Burch Reva Chestnut Leopard Ballet Flats CheapTory Burch White Yellow Handbags Cheap 9hLjb hollister paris 7sCig ghd baratas 4bGjn ugg boots

    Reply
  • ugg boots sfebzs http://www.discountuggsbootsxs.com/

    Posted by Suttoncme on 01/30/2013 06:34pm

    2uMyy cheap nike shoes tNti Michael Kors outlet uWif ugg boots 4dIhd monster beats 5cJlt New Orleans Hornets NBA Hats-Blue Wholesale Sell 1lKwk ugg 7vYxe burberry outlet 6iIrw longchamp 6yXgc nike shoes online 2rFas cheap ugg boots 1yDty monster beats 4dTkz ugg 0qIzx GHD Hair Straightener 6oShb 6vEuv

    Reply
  • ghd australia kgwxyh http://www.cheapfashionshoesas.com/

    Posted by Mandybym on 01/29/2013 06:04am

    2tPlw bottes ugg aWrx ¥È¥ê©`¥Ð©`¥Á ¥Ð¥Ã¥° oVye nike norge 6wJvy cheap toms shoes 0gQnu hollister outlet uk 3qGiw bottes ugg pas cher 7cDnw longchamps 8xApu louis vuitton outlet 6tWft Michael Kors 3ySgf christian louboutin norge 2aQmw ugg sale 8hWuw nfl football jerseys 2iXzj 8kHcc GHD Pas Cher 3fEbg ugg sale

    Reply
  • ugg boots vwdjcs http://www.cheapfashionshoesas.com/

    Posted by Suttonfdn on 01/27/2013 12:21pm

    5eVoq nike online store hBqh Michael Kors outlet yQvc ugg boots 4aUgn beats for sale 2dMcs Cheap nfl jerseys 9yQtq uggs p? nett 2mIph burberry outlet 2pHwc longchamp bags 6lUcw nike air max 5iOxn cheap ugg boots 1bXax monster headphones 1iZiw ugg baratas 5xWeh ghd 3tIyl 4dRtm

    Reply
  • Loading, Please Wait ...

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: October 29, 2014 @ 11:00 a.m. ET / 8:00 a.m. PT Are you interested in building a cognitive application using the power of IBM Watson? Need a platform that provides speed and ease for rapidly deploying this application? Join Chris Madison, Watson Solution Architect, as he walks through the process of building a Watson powered application on IBM Bluemix. Chris will talk about the new Watson Services just released on IBM bluemix, but more importantly he will do a step by step cognitive …

  • In support of their business continuity and disaster recovery plans, many midsized companies endeavor to avoid putting all their eggs in one basket. Understanding the critical role of last-mile connectivity and always available Internet access for their enterprises, savvy firms utilize redundant connections from multiple service providers. Despite the good intentions, their Internet connectivity risk may still be in a single basket. That is because internet service providers (ISPs) and competitive local …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds