libconfig
*********

Introduction
************

Libconfig is a library for reading, manipulating, and writing structured configuration files. The library features a fully reentrant parser and includes bindings for both the C and C++ programming languages.

The library runs on modern POSIX-compilant systems, such as Linux, Solaris, and Mac OS X (Darwin), as well as on Microsoft Windows 2000/XP and later (with either Microsoft Visual Studio 2005 or later, or the GNU toolchain via the MinGW environment).

Why Another Configuration File Library?
=======================================

There are several open-source configuration file libraries available as of this writing. This library was written because each of those libraries falls short in one or more ways. The main features of libconfig that set it apart from the other libraries are:

  * A fully reentrant parser. Independent configurations can be parsed in concurrent threads at the same time.

  * Both C and C++ bindings, as well as hooks to allow for the creation of wrappers in other languages.

  * A simple, structured configuration file format that is more readable and compact than XML and more flexible than the obsolete but prevalent Windows ``INI'' file format.

  * A low-footprint implementation (just 37K for the C library and 76K for the C++ library) that is suitable for memory-constrained systems.

  * Proper documentation.

Using the Library from a C Program
==================================

To use the library from C code, include the following preprocessor directive in your source files:

     #include <libconfig.h>

To link with the library, specify -lconfig as an argument to the linker.

Using the Library from a C++ Program
====================================

To use the library from C++, include the following preprocessor directive in your source files:

     #include <libconfig.h++>

Or, alternatively:

     #include <libconfig.hh>

The C++ API classes are defined in the namespace libconfig, hence the following statement may optionally be used:

     using namespace libconfig;

To link with the library, specify -lconfig++ as an argument to the linker.

Multithreading Issues
=====================

Libconfig is fully reentrant; the functions in the library do not make use of global variables and do not maintain state between successive calls. Therefore two independent configurations may be safely manipulated concurrently by two distinct threads.

Libconfig is not thread-safe. The library is not aware of the presence of threads and knows nothing about the host system's threading model. Therefore, if an instance of a configuration is to be accessed from multiple threads, it must be suitably protected by synchronization mechanisms like read-write locks or mutexes; the standard rules for safe multithreaded access to shared data must be observed.

Libconfig is not async-safe. Calls should not be made into the library from signal handlers, because some of the C library routines that it uses may not be async-safe.

Libconfig is not guaranteed to be cancel-safe. Since it is not aware of the host system's threading model, the library does not contain any thread cancellation points. In most cases this will not be an issue for multithreaded programs. However, be aware that some of the routines in the library (namely those that read/write configurations from/to files or streams) perform I/O using C library routines which may potentially block; whether or not these C library routines are cancel-safe depends on the host system.

Internationalization Issues
===========================

Libconfig does not natively support Unicode configuration files, but string values may contain Unicode text encoded in UTF-8; such strings will be treated as ordinary 8-bit ASCII text by the library. It is the responsibility of the calling program to perform the necessary conversions to/from wide (wchar_t) strings using the wide string conversion functions such as mbsrtowcs() and wcsrtombs() or the iconv() function of the libiconv library.

The textual representation of a floating point value varies by locale. However, the libconfig grammar specifies that floating point values are represented using a period (`.') as the radix symbol; this is consistent with the grammar of most programming languages. When a configuration is read in or written out, libconfig temporarily changes the LC_NUMERIC category of the locale of the calling thread to the ``C'' locale to ensure consistent handling of floating point values regardless of the locale(s) in use by the calling program.

Note that the MinGW environment does not (as of this writing) provide functions for changing the locale of the calling thread. Therefore, when using libconfig in that environment, the calling program is responsible for changing the LC_NUMERIC category of the locale to the "C" locale before reading or writing a configuration.

Compiling Using pkg-config
==========================

On UNIX systems you can use the pkg-config utility (version 0.20 or later) to automatically select the appropriate compiler and linker switches for libconfig. Ensure that the environment variable PKG_CONFIG_PATH contains the absolute path to the lib/pkgconfig subdirectory of the libconfig installation. Then, you can compile and link C programs with libconfig as follows:

     gcc `pkg-config --cflags libconfig` myprogram.c -o myprogram \
         `pkg-config --libs libconfig`

And similarly, for C++ programs:

     g++ `pkg-config --cflags libconfig++` myprogram.cpp -o myprogram \
         `pkg-config --libs libconfig++`

Note the backticks in the above examples.

When using autoconf, the PKG_CHECK_MODULES m4 macro may be used to check for the presence of a given version of libconfig, and set the appropriate Makefile variables automatically. For example:

     PKG_CHECK_MODULES([LIBCONFIGXX], [libconfig++ >= 1.4],,
       AC_MSG_ERROR([libconfig++ 1.4 or newer not found.])
     )

In the above example, if libconfig++ version 1.4 or newer is found, the Makefile variables LIBCONFIGXX_LIBS and LIBCONFIGXX_CFLAGS will be set to the appropriate compiler and linker flags for compiling with libconfig, and if it is not found, the configure script will abort with an error to that effect.

Version Test Macros
===================

The libconfig.h header declares the following macros:

 -- Macro: LIBCONFIG_VER_MAJOR
 -- Macro: LIBCONFIG_VER_MINOR
 -- Macro: LIBCONFIG_VER_REVISION

     These macros represent the major version, minor version, and revision of the libconfig library. For example, in libconfig 1.4 these are defined as 1, 4, and 0, respectively. These macros can be used in preprocessor directives to determine which libconfig features and/or APIs are present. For example:

          #if (((LIBCONFIG_VER_MAJOR == 1) && (LIBCONFIG_VER_MINOR >= 4)) \
               || (LIBCONFIG_VER_MAJOR > 1))
            /* use features present in libconfig 1.4 and later */
          #endif

     These macros were introduced in libconfig 1.4.

Similarly, the libconfig.h++ header declares the following macros:

 -- Macro: LIBCONFIGXX_VER_MAJOR
 -- Macro: LIBCONFIGXX_VER_MINOR
 -- Macro: LIBCONFIGXX_VER_REVISION

     These macros represent the major version, minor version, and revision of the libconfig++ library.

Configuration Files
*******************

Libconfig supports structured, hierarchical configurations. These configurations can be read from and written to files and manipulated in memory.

A configuration consists of a group of settings, which associate names with values. A value can be one of the following:

  * A scalar value: integer, 64-bit integer, floating-point number, boolean, or string

  * An array, which is a sequence of scalar values, all of which must have the same type

  * A group, which is a collection of settings

  * A list, which is a sequence of values of any type, including other lists

Consider the following configuration file for a hypothetical GUI application, which illustrates all of the elements of the configuration file grammar.

     # Example application configuration file

     version = "1.0";

     application:
     {
       window:
       {
         title = "My Application";
         size = { w = 640; h = 480; };
         pos = { x = 350; y = 250; };
       };

       list = ( ( "abc", 123, true ), 1.234, ( /* an empty list */ ) );

       books = ( { title  = "Treasure Island";
                   author = "Robert Louis Stevenson";
                   price  = 29.95;
                   qty    = 5; },
                 { title  = "Snow Crash";
                   author = "Neal Stephenson";
                   price  = 9.99;
                   qty    = 8; } );

       misc:
       {
         pi = 3.141592654;
         bigint = 9223372036854775807L;
         columns = [ "Last Name", "First Name", "MI" ];
         bitmask = 0x1FC3;	// hex
         umask = 0027;	// octal. Range limited to that of "int"
       };
     };

Settings can be uniquely identified within the configuration by a path. The path is a dot-separated sequence of names, beginning at a top-level group and ending at the setting itself. Each name in the path is the name of a setting; if the setting has no name because it is an element in a list or array, an integer index in square brackets can be used as the name.

For example, in our hypothetical configuration file, the path to the x setting is application.window.pos.x; the path to the version setting is simply version; and the path to the title setting of the second book in the books list is application.books.[1].title.

The datatype of a value is determined from the format of the value itself. If the value is enclosed in double quotes, it is treated as a string. If it looks like an integer or floating point number, it is treated as such. If it is one of the values TRUE, true, FALSE, or false (or any other mixed-case version of those tokens, e.g., True or FaLsE), it is treated as a boolean. If it consists of a comma-separated list of values enclosed in square brackets, it is treated as an array. And if it consists of a comma-separated list of values enclosed in parentheses, it is treated as a list. Any value which does not meet any of these criteria is considered invalid and results in a parse error.

All names are case-sensitive. They may consist only of alphanumeric characters, dashes (-), underscores (_), and asterisks (*), and must begin with a letter or asterisk. No other characters are allowed.

In C and C++, integer, 64-bit integer, floating point, and string values are mapped to the native types int, long long, double, and const char *, respectively. The boolean type is mapped to int in C and bool in C++.

The following sections describe the elements of the configuration file grammar in additional detail.

Settings
========

A setting has the form:

name = value ;

or:

name : value ;

The trailing semicolon is optional. Whitespace is not significant.

The value may be a scalar value, an array, a group, or a list.

Groups
======

A group has the form:

{ settings ... }

Groups can contain any number of settings, but each setting must have a unique name within the group.

Arrays
======

An array has the form:

[ value, value ... ]

An array may have zero or more elements, but the elements must all be scalar values of the same type.

The last element in an array may be followed by a comma, which will be ignored.

Lists
=====

A list has the form:

( value, value ... )

A list may have zero or more elements, each of which can be a scalar value, an array, a group, or another list.

The last element in a list may be followed by a comma, which will be ignored.

Integer Values
==============

Integers can be represented in one of two ways: as a series of one or more decimal digits (0 - 9), with an optional leading sign character (+ or -); or as a hexadecimal value consisting of the characters 0x followed by a series of one or more hexadecimal digits (0 - 9, A - F, a - f). Additionally, octal notation integers (that is, those having a leading zero with non-zero value) are also allowed.

64-bit Integer Values
=====================

Long long (64-bit) integers are represented identically to integers, except that an `L' character is appended to indicate a 64-bit value. For example, 0L indicates a 64-bit integer value 0.  As of version 1.5 of the library, the trailing `L' is optional; if the integer value exceeds the range of a 32-bit integer, it will automatically be interpreted as a 64-bit integer.

The integer and 64-bit integer setting types are interchangeable to the extent that a conversion between the corresponding native types would not result in an overflow or underflow. For example, a long long value can be written to a setting that has an integer type, if that value is within the range of an int. This rule applies to every API function or method that reads a value from or writes a value to a setting: if the type conversion would not result in an overflow or underflow, then the call will succeed, and otherwise it will fail. This behavior was not well-defined prior to version 1.7 of the library.

Floating Point Values
=====================

Floating point values consist of a series of one or more digits, one decimal point, an optional leading sign character (+ or -), and an optional exponent. An exponent consists of the letter E or e, an optional sign character, and a series of one or more digits.

Boolean Values
==============

Boolean values may have one of the following values: true, false, or any mixed-case variation thereof.

String Values
=============

String values consist of arbitrary text delimited by double quotes. Literal double quotes can be escaped by preceding them with a backslash: \". The escape sequences \\, \f, \n, \r, and \t are also recognized, and have the usual meaning.

In addition, the \x escape sequence is supported; this sequence must be followed by exactly two hexadecimal digits, which represent an 8-bit ASCII value. For example, \xFF represents the character with ASCII code 0xFF.

No other escape sequences are currently supported.

Adjacent strings are automatically concatenated, as in C/C++ source code. This is useful for formatting very long strings as sequences of shorter strings. For example, the following constructs are equivalent:

  * "The quick brown fox jumped over the lazy dog."

  * "The quick brown fox"

     " jumped over the lazy dog."

  * "The quick" /* comment */ " brown fox " // another comment

     "jumped over the lazy dog."

Comments
========

Three types of comments are allowed within a configuration:

  * Script-style comments. All text beginning with a # character to the end of the line is ignored.

  * C-style comments. All text, including line breaks, between a starting /* sequence and an ending */ sequence is ignored.

  * C++-style comments. All text beginning with a // sequence to the end of the line is ignored.

As expected, comment delimiters appearing within quoted strings are treated as literal text.

Comments are ignored when the configuration is read in, so they are not treated as part of the configuration. Therefore if the configuration is written back out to a stream, any comments that were present in the original configuration will be lost.

Include Directives
==================

A configuration file may ``include'' the contents of other files using an include directive. This directive has the effect of inlining the contents of the named file(s) at the point of inclusion.

An include directive must appear on its own line in the input. It has the form:

@include "path"

The interpretation of path depends on the currently registered include function. The default include function prepends the include directory, if any, to path, and then interprets the result as a single, literal file path. The application may supply its own include function which does variable substitution, wildcard expansion, or other transformations, returning a list of zero or more paths to files whose contents should be inlined at the point of inclusion.

Any backslashes or double quotes in the path must be escaped as \\ and \", respectively.

For example, consider the following two configuration files:

     # file: quote.cfg
     quote = "Criticism may not be agreeable, but it is necessary."
             " It fulfils the same function as pain in the human"
             " body. It calls attention to an unhealthy state of"
             " things.\n"
             "\t--Winston Churchill";

     # file: test.cfg
     info: {
       name = "Winston Churchill";
       @include "quote.cfg"
       country = "UK";
     };

The resulting configuration will be equivalent to one in which the contents of the file quote.cfg appeared at the point where the include directive is placed.

Include files may be nested to a maximum of 10 levels; exceeding this limit results in a parse error.

When the path argument to an @include directive is a relative path, then it will be interpreted as being relative to the include directory that has been been set by means of config_set_include_dir(). If no include directory has been set, then it will be taken as being relative to the program's current working directory.

Like comments, include directives are not part of the configuration file syntax. They are processed before the configuration itself is parsed. Therefore, they are not preserved when the configuration is written back out to a stream. There is presently no support for programmatically inserting include directives into a configuration.

The C API
*********

This chapter describes the C library API. The type config_t represents a configuration, and the type config_setting_t represents a configuration setting.

The boolean values CONFIG_TRUE and CONFIG_FALSE are macros defined as (1) and (0), respectively.

 -- Function: void config_init (config_t * CONFIG)
 -- Function: void config_destroy (config_t * CONFIG)

     These functions initialize and destroy the configuration object CONFIG.

     config_init() initializes the config_t structure pointed to by CONFIG as a new, empty configuration.

     config_destroy() destroys the configuration CONFIG, deallocating all memory associated with the configuration, but does not attempt to deallocate the config_t structure itself.

 -- Function: void config_clear (config_t * CONFIG)

     Since v1.7

     This function clears the configuration CONFIG. All child settings of the root setting are recursively destroyed. All other attributes of the configuration are left unchanged.

 -- Function: int config_read (config_t * CONFIG, FILE * STREAM)

     This function reads and parses a configuration from the given STREAM into the configuration object CONFIG. It returns CONFIG_TRUE on success, or CONFIG_FALSE on failure; the config_error_text(), config_error_file(), config_error_line(), and config_error_type() functions, described below, can be used to obtain information about the error.

 -- Function: int config_read_file (config_t * CONFIG, const char * FILENAME)

     This function reads and parses a configuration from the file named FILENAME into the configuration object CONFIG. It returns CONFIG_TRUE on success, or CONFIG_FALSE on failure; the config_error_text() and config_error_line() functions, described below, can be used to obtain information about the error.

 -- Function: int config_read_string (config_t * CONFIG, const char * STR)

     This function reads and parses a configuration from the string STR into the configuration object CONFIG. It returns CONFIG_TRUE on success, or CONFIG_FALSE on failure; the config_error_text() and config_error_line() functions, described below, can be used to obtain information about the error.

 -- Function: void config_write (const config_t * CONFIG, FILE * STREAM)

     This function writes the configuration CONFIG to the given STREAM.

 -- Function: int config_write_file (config_t * CONFIG, const char * FILENAME)

     This function writes the configuration CONFIG to the file named FILENAME. It returns CONFIG_TRUE on success, or CONFIG_FALSE on failure.

 -- Function: const char * config_error_text (const config_t * CONFIG)
 -- Function: const char * config_error_file (const config_t * CONFIG)
 -- Function: int config_error_line (const config_t * CONFIG)

     These functions, which are implemented as macros, return the text, filename, and line number of the parse error, if one occurred during a call to config_read(), config_read_string(), or config_read_file(). Storage for the strings returned by config_error_text() and config_error_file() are managed by the library and released automatically when the configuration is destroyed; these strings must not be freed by the caller. If the error occurred in text that was read from a string or stream, config_error_file() will return NULL.

 -- Function: config_error_t config_error_type (const config_t * CONFIG)
     This function, which is implemented as a macro, returns the type of error that occurred during the last call to one of the read or write functions. The CONFIG_ERROR_T type is an enumeration with the following values: CONFIG_ERR_NONE, CONFIG_ERR_FILE_IO, CONFIG_ERR_PARSE. These represent success, a file I/O error, and a parsing error, respectively.

 -- Function: void config_set_include_dir (config_t *CONFIG, const char *INCLUDE_DIR)
 -- Function: const char * config_get_include_dir (const config_t *CONFIG)

     config_set_include_dir() specifies the include directory, INCLUDE_DIR, relative to which the files specified in @include directives will be located for the configuration CONFIG. By default, there is no include directory, and all include files are expected to be relative to the current working directory. If INCLUDE_DIR is NULL, the default behavior is reinstated.

     For example, if the include directory is set to /usr/local/etc, the include directive @include "configs/extra.cfg" would include the file /usr/local/etc/configs/extra.cfg.

     config_get_include_dir() returns the current include directory for the configuration CONFIG, or NULL if none is set.

 -- Function: void config_set_include_func (config_include_fn_t FUNC)

     Since v1.7

     Specifies the include function FUNC to use when processing include directives. If FUNC is NULL, the default include function, config_default_include_func(), will be reinstated.

     The type config_include_fn_t is a type alias for a function whose signature is:

      -- Function: const char ** func (config_t *CONFIG, const char *INCLUDE_DIR, const char *PATH, const char **ERROR)

          The function receives the configuration CONFIG, the configuration's current include directory INCLUDE_DIR, the argument to the include directive PATH; and a pointer at which to return an error message ERROR.

          On success, the function should return a NULL-terminated array of paths. Any relative paths must be relative to the program's current working directory. The contents of these files will be inlined at the point of inclusion, in the order that the paths appear in the array. Both the array and its elements should be heap allocated; the library will take ownership of and eventually free the strings in the array and the array itself.

          On failure, the function should return NULL and set *ERROR to a static error string which should be used as the parse error for the configuration; the library does not take ownership of or free this string.

          The default include function, config_default_include_func(), simply returns a NULL-terminated array containing either a copy of PATH if it's an absolute path, or a concatenation of INCLUDE_DIR and PATH if it's a relative path.

     Application-supplied include functions can perform custom tasks like wildcard expansion or variable substitution. For example, consider the include directive:

          @include "configs/*.cfg"

     The include function would be invoked with the path configs/*.cfg and could do wildcard expansion on that path, returning a list of paths to files with the file extension .cfg in the subdirectory configs. Each of these files would then be inlined at the location of the include directive.

     Tasks like wildcard expansion and variable substitution are non-trivial to implement and typically require platform-specific code. In the interests of keeping the library as compact and platform-independent as possible, implementations of such include functions are not included.

 -- Function: unsigned short config_get_float_precision(config_t *CONFIG)
 -- Function: void config_set_float_precision(config_t *CONFIG, unsigned short DIGITS)

     Since v1.6

     These functions get and set the number of decimal digits to output after the radix character when writing the configuration to a file or stream.

     Valid values for DIGITS range from 0 (no decimals) to about 15 (implementation defined). This parameter has no effect on parsing.

     The default float precision is 6.

 -- Function: int config_get_options (config_t *CONFIG)
 -- Function: void config_set_options (config_t *CONFIG, int OPTIONS)

     These functions get and set the options for the configuration CONFIG. The options affect how configurations are read and written. The following options are defined:

     CONFIG_OPTION_AUTOCONVERT
          Turning this option on enables number auto-conversion for the configuration. When this feature is enabled, an attempt to retrieve a floating point setting's value into an integer (or vice versa), or store an integer to a floating point setting's value (or vice versa) will cause the library to silently perform the necessary conversion (possibly leading to loss of data), rather than reporting failure. By default this option is turned off.

     CONFIG_OPTION_SEMICOLON_SEPARATORS
          This option controls whether a semicolon (`;') is output after each setting when the configuration is written to a file or stream. (The semicolon separators are optional in the configuration syntax.) By default this option is turned on.

     CONFIG_OPTION_COLON_ASSIGNMENT_FOR_GROUPS
          This option controls whether a colon (`:') is output between each group setting's name and its value when the configuration is written to a file or stream. If the option is turned off, an equals sign (`=') is output instead. (These tokens are interchangeable in the configuration syntax.) By default this option is turned on.

     CONFIG_OPTION_COLON_ASSIGNMENT_FOR_NON_GROUPS
          This option controls whether a colon (`:') is output between each non-group setting's name and its value when the configuration is written to a file or stream. If the option is turned off, an equals sign (`=') is output instead. (These tokens are interchangeable in the configuration syntax.) By default this option is turned off.

     CONFIG_OPTION_OPEN_BRACE_ON_SEPARATE_LINE
          This option controls whether an open brace (`{') will be written on its own line when the configuration is written to a file or stream. If the option is turned off, the brace will be written at the end of the previous line. By default this option is turned on.

     CONFIG_OPTION_ALLOW_SCIENTIFIC_NOTATION
          (Since v1.7) This option controls whether scientific notation may be used as appropriate when writing floating point values (corresponding to printf() %g format) or should never be used (corresponding to printf() %f format). By default this option is turned off.

     CONFIG_OPTION_FSYNC
          (Since v1.7.1) This option controls whether the config_write_file() function performs an fsync operation after writing the configuration and before closing the file. By default this option is turned off.

     CONFIG_OPTION_ALLOW_OVERRIDES
          (Since v1.7.3) This option controls whether duplicate settings override previous settings with the same name. If this option is turned off, duplicate settings are rejected. By default this option is turned off.

 -- Function: int config_get_option (config_t *CONFIG, int OPTION)
 -- Function: void config_set_option (config_t *CONFIG, int OPTION, int FLAG)

     Since v1.7

     These functions get and set the given OPTION of the configuration CONFIG. The option is enabled if FLAG is CONFIG_TRUE and disabled if it is CONFIG_FALSE.

     See config_set_options() above for the list of available options.

 -- Function: int config_get_auto_convert (const config_t *CONFIG)
 -- Function: void config_set_auto_convert (config_t *CONFIG, int FLAG)

     These functions get and set the CONFIG_OPTION_AUTO_CONVERT option. They are obsoleted by the config_set_option() and config_get_option() functions described above.

 -- Function: short config_get_default_format (config_t * CONFIG)
 -- Function: void config_set_default_format (config_t * CONFIG, short FORMAT)

     These functions, which are implemented as macros, get and set the default external format for settings in the configuration CONFIG. If a non-default format has not been set for a setting with config_setting_set_format(), this configuration-wide default format will be used instead when that setting is written to a file or stream.

 -- Function: unsigned short config_get_tab_width (const config_t * CONFIG)
 -- Function: void config_set_tab_width (config_t * CONFIG, unsigned short WIDTH)

     These functions, which are implemented as macros, get and set the tab width for the configuration CONFIG. The tab width affects the formatting of the configuration when it is written to a file or stream: each level of nesting is indented by WIDTH spaces, or by a single tab character if WIDTH is 0. The tab width has no effect on parsing.

     Valid tab widths range from 0 to 15. The default tab width is 2.

 -- Function: int config_lookup_int (const config_t * CONFIG, const char * PATH, int * VALUE)
 -- Function: int config_lookup_int64 (const config_t * CONFIG, const char * PATH, long long * VALUE)
 -- Function: int config_lookup_float (const config_t * CONFIG, const char * PATH, double * VALUE)
 -- Function: int config_lookup_bool (const config_t * CONFIG, const char * PATH, int * VALUE)
 -- Function: int config_lookup_string (const config_t * CONFIG, const char * PATH, const char ** VALUE)

     These functions look up the value of the setting in the configuration CONFIG specified by the path PATH. They store the value of the setting at VALUE and return CONFIG_TRUE on success. If the setting was not found or if the type of the value did not match the type requested, they leave the data pointed to by VALUE unmodified and return CONFIG_FALSE.

     Storage for the string returned by config_lookup_string() is managed by the library and released automatically when the setting is destroyed or when the setting's value is changed; the string must not be freed by the caller.

 -- Function: config_setting_t * config_lookup (const config_t * CONFIG, const char * PATH)

     This function locates the setting in the configuration CONFIG specified by the path PATH. It returns a pointer to the config_setting_t structure on success, or NULL if the setting was not found.

 -- Function: config_setting_t * config_setting_lookup (const config_setting_t * SETTING, const char * PATH)

     This function locates a setting by a path PATH relative to the setting SETTING. It returns a pointer to the config_setting_t structure on success, or NULL if the setting was not found.

 -- Function: int config_setting_get_int (const config_setting_t * SETTING)
 -- Function: long long config_setting_get_int64 (const config_setting_t * SETTING)
 -- Function: double config_setting_get_float (const config_setting_t * SETTING)
 -- Function: int config_setting_get_bool (const config_setting_t * SETTING)
 -- Function: const char * config_setting_get_string (const config_setting_t * SETTING)

     These functions return the value of the given SETTING. If the type of the setting does not match the type requested, a 0 or NULL value is returned. Storage for the string returned by config_setting_get_string() is managed by the library and released automatically when the setting is destroyed or when the setting's value is changed; the string must not be freed by the caller.

 -- Function: int config_setting_set_int (config_setting_t * SETTING, int VALUE)
 -- Function: int config_setting_set_int64 (config_setting_t * SETTING, long long VALUE)
 -- Function: int config_setting_set_float (config_setting_t * SETTING, double VALUE)
 -- Function: int config_setting_set_bool (config_setting_t * SETTING, int VALUE)
 -- Function: int config_setting_set_string (config_setting_t * SETTING, const char * VALUE)

     These functions set the value of the given SETTING to VALUE. On success, they return CONFIG_TRUE. If the setting does not match the type of the value, they return CONFIG_FALSE. config_setting_set_string() makes a copy of the passed string VALUE, so it may be subsequently freed or modified by the caller without affecting the value of the setting.

 -- Function: int config_setting_lookup_int (const config_setting_t * SETTING, const char * NAME, int * VALUE)
 -- Function: int config_setting_lookup_int64 (const config_setting_t * SETTING, const char * NAME, long long * VALUE)
 -- Function: int config_setting_lookup_float (const config_setting_t * SETTING, const char * NAME, double * VALUE)
 -- Function: int config_setting_lookup_bool (const config_setting_t * SETTING, const char * NAME, int * VALUE)
 -- Function: int config_setting_lookup_string (const config_setting_t * SETTING, const char * NAME, const char ** VALUE)

     These functions look up the value of the child setting named NAME of the setting SETTING. They store the value at VALUE and return CONFIG_TRUE on success. If the setting was not found or if the type of the value did not match the type requested, they leave the data pointed to by VALUE unmodified and return CONFIG_FALSE.

     Storage for the string returned by config_setting_lookup_string() is managed by the library and released automatically when the setting is destroyed or when the setting's value is changed; the string must not be freed by the caller.

 -- Function: short config_setting_get_format (config_setting_t * SETTING)
 -- Function: int config_setting_set_format (config_setting_t * SETTING, short FORMAT)

     These functions get and set the external format for the setting SETTING.

     The FORMAT must be one of the constants CONFIG_FORMAT_DEFAULT or CONFIG_FORMAT_HEX. All settings support the CONFIG_FORMAT_DEFAULT format. The CONFIG_FORMAT_HEX format specifies hexadecimal formatting for integer values, and hence only applies to settings of type CONFIG_TYPE_INT and CONFIG_TYPE_INT64.  If FORMAT is invalid for the given setting, it is ignored.

     If a non-default format has not been set for the setting, config_setting_get_format() returns the default format for the configuration, as set by config_set_default_format().

     config_setting_set_format() returns CONFIG_TRUE on success and CONFIG_FALSE on failure.

 -- Function: config_setting_t * config_setting_get_member (config_setting_t * SETTING, const char * NAME)

     This function fetches the child setting named NAME from the group SETTING. It returns the requested setting on success, or NULL if the setting was not found or if SETTING is not a group.

 -- Function: config_setting_t * config_setting_get_elem (const config_setting_t * SETTING, unsigned int INDEX)

     This function fetches the element at the given index INDEX in the setting SETTING, which must be an array, list, or group. It returns the requested setting on success, or NULL if INDEX is out of range or if SETTING is not an array, list, or group.

 -- Function: int config_setting_get_int_elem (const config_setting_t * SETTING, int INDEX)
 -- Function: long long config_setting_get_int64_elem (const config_setting_t * SETTING, int INDEX)
 -- Function: double config_setting_get_float_elem (const config_setting_t * SETTING, int INDEX)
 -- Function: int config_setting_get_bool_elem (const config_setting_t * SETTING, int INDEX)
 -- Function: const char * config_setting_get_string_elem (const config_setting_t * SETTING, int INDEX)

     These functions return the value at the specified index INDEX in the setting SETTING. If the setting is not an array or list, or if the type of the element does not match the type requested, or if INDEX is out of range, they return 0 or NULL. Storage for the string returned by config_setting_get_string_elem() is managed by the library and released automatically when the setting is destroyed or when its value is changed; the string must not be freed by the caller.

 -- Function: config_setting_t * config_setting_set_int_elem (config_setting_t * SETTING, int INDEX, int VALUE)
 -- Function: config_setting_t * config_setting_set_int64_elem (config_setting_t * SETTING, int INDEX, long long VALUE)
 -- Function: config_setting_t * config_setting_set_float_elem (config_setting_t * SETTING, int INDEX, double VALUE)
 -- Function: config_setting_t * config_setting_set_bool_elem (config_setting_t * SETTING, int INDEX, int VALUE)
 -- Function: config_setting_t * config_setting_set_string_elem (config_setting_t * SETTING, int INDEX, const char * VALUE)

     These functions set the value at the specified index INDEX in the setting SETTING to VALUE. If INDEX is negative, a new element is added to the end of the array or list. On success, these functions return a pointer to the setting representing the element. If the setting is not an array or list, or if the setting is an array and the type of the array does not match the type of the value, or if INDEX is out of range, they return NULL. config_setting_set_string_elem() makes a copy of the passed string VALUE, so it may be subsequently freed or modified by the caller without affecting the value of the setting.

 -- Function: config_setting_t * config_setting_add (config_setting_t * PARENT, const char * NAME, int TYPE)

     This function adds a new child setting or element to the setting PARENT, which must be a group, array, or list. If PARENT is an array or list, the NAME parameter is ignored and may be NULL.

     The function returns the new setting on success, or NULL if PARENT is not a group, array, or list; or if there is already a child setting of PARENT named NAME; or if TYPE is invalid. If TYPE is a scalar type, the new setting will have a default value of 0, 0.0, false, or NULL, as appropriate.

 -- Function: int config_setting_remove (config_setting_t * PARENT, const char * NAME)

     This function removes and destroys the setting named NAME from the parent setting PARENT, which must be a group. Any child settings of the setting are recursively destroyed as well.

     The NAME parameter can also specify a setting path relative to the provided PARENT. (In that case, the setting will be looked up and removed.)

     The function returns CONFIG_TRUE on success. If PARENT is not a group, or if it has no setting with the given name, it returns CONFIG_FALSE.

 -- Function: int config_setting_remove_elem (config_setting_t * PARENT, unsigned int INDEX)

     This function removes the child setting at the given index INDEX from the setting PARENT, which must be a group, list, or array. Any child settings of the removed setting are recursively destroyed as well.

     The function returns CONFIG_TRUE on success. If PARENT is not a group, list, or array, or if INDEX is out of range, it returns CONFIG_FALSE.

 -- Function: config_setting_t * config_root_setting (const config_t * CONFIG)

     This function, which is implemented as a macro, returns the root setting for the configuration CONFIG. The root setting is a group.

 -- Function: const char * config_setting_name (const config_setting_t * SETTING)

     This function returns the name of the given SETTING, or NULL if the setting has no name. Storage for the returned string is managed by the library and released automatically when the setting is destroyed; the string must not be freed by the caller.

 -- Function: config_setting_t * config_setting_parent (const config_setting_t * SETTING)

     This function returns the parent setting of the given SETTING, or NULL if SETTING is the root setting.

 -- Function: int config_setting_is_root (const config_setting_t * SETTING)

     This function returns CONFIG_TRUE if the given SETTING is the root setting, and CONFIG_FALSE otherwise.

 -- Function: int config_setting_index (const config_setting_t * SETTING)

     This function returns the index of the given SETTING within its parent setting. If SETTING is the root setting, this function returns -1.

 -- Function: int config_setting_length (const config_setting_t * SETTING)

     This function returns the number of settings in a group, or the number of elements in a list or array. For other types of settings, it returns 0.

 -- Function: int config_setting_type (const config_setting_t * SETTING)

     This function returns the type of the given SETTING. The return value is one of the constants CONFIG_TYPE_INT, CONFIG_TYPE_INT64, CONFIG_TYPE_FLOAT, CONFIG_TYPE_STRING, CONFIG_TYPE_BOOL, CONFIG_TYPE_ARRAY, CONFIG_TYPE_LIST, or CONFIG_TYPE_GROUP.

 -- Function: int config_setting_is_group (const config_setting_t * SETTING)
 -- Function: int config_setting_is_array (const config_setting_t * SETTING)
 -- Function: int config_setting_is_list (const config_setting_t * SETTING)

     These convenience functions, which are implemented as macros, test if the setting SETTING is of a given type. They return CONFIG_TRUE or CONFIG_FALSE.

 -- Function: int config_setting_is_aggregate (const config_setting_t * SETTING)
 -- Function: int config_setting_is_scalar (const config_setting_t * SETTING)
 -- Function: int config_setting_is_number (const config_setting_t * SETTING)

     These convenience functions, some of which are implemented as macros, test if the setting SETTING is of an aggregate type (a group, array, or list), of a scalar type (integer, 64-bit integer, floating point, boolean, or string), and of a number (integer, 64-bit integer, or floating point), respectively. They return CONFIG_TRUE or CONFIG_FALSE.

 -- Function: const char * config_setting_source_file (const config_setting_t * SETTING)

     This function returns the name of the file from which the setting SETTING was read, or NULL if the setting was not read from a file. This information is useful for reporting application-level errors. Storage for the returned string is managed by the library and released automatically when the configuration is destroyed; the string must not be freed by the caller.

 -- Function: unsigned int config_setting_source_line (const config_setting_t * SETTING)

     This function returns the line number of the configuration file or stream at which the setting SETTING was read, or 0 if no line number is available. This information is useful for reporting application-level errors.

 -- Function: void config_set_hook (config_t * CONFIG, void * HOOK)
 -- Function: void * config_get_hook (const config_t * CONFIG)

     Since v1.7

     These functions make it possible to attach arbitrary data to a configuration structure, for instance a ``wrapper'' or ``peer'' object written in another programming language.

 -- Function: void config_setting_set_hook (config_setting_t * SETTING, void * HOOK)
 -- Function: void * config_setting_get_hook (const config_setting_t * SETTING)

     These functions make it possible to attach arbitrary data to each setting structure, for instance a ``wrapper'' or ``peer'' object written in another programming language. The destructor function, if one has been supplied via a call to config_set_destructor(), will be called by the library to dispose of this data when the setting itself is destroyed. There is no default destructor.

 -- Function: void config_set_destructor (config_t * CONFIG, void (* DESTRUCTOR)(void *))

     This function assigns the destructor function DESTRUCTOR for the configuration CONFIG. This function accepts a single void * argument and has no return value. See config_setting_set_hook() above for more information.

The C++ API
***********

This chapter describes the C++ library API. The class Config represents a configuration, and the class Setting represents a configuration setting. Note that by design, neither of these classes provides a public copy constructor or assignment operator. Therefore, instances of these classes may only be passed between functions via references or pointers.

The library defines a group of exceptions, all of which extend the common base exception ConfigException.

A SettingTypeException is thrown when the type of a setting's value does not match the type requested.

 -- Method on SettingTypeException: SettingTypeException (const Setting &SETTING)
 -- Method on SettingTypeException: SettingTypeException (const Setting &SETTING, int INDEX)
 -- Method on SettingTypeException: SettingTypeException (const Setting &SETTING, const char *NAME)

     These methods construct SettingTypeException objects for the given SETTING and/or member INDEX or NAME.

A SettingNotFoundException is thrown when a setting is not found.

 -- Method on SettingNotFoundException: SettingNotFoundException (const Setting &SETTING, int INDEX)
 -- Method on SettingNotFoundException: SettingNotFoundException (const Setting &SETTING, const char *NAME)
 -- Method on SettingNotFoundException: SettingNotFoundException (const char *PATH)

     These methods construct SettingTypeException objects for the given SETTING and member INDEX or NAME, or path PATH.

A SettingNameException is thrown when an attempt is made to add a new setting with a non-unique or invalid name.

 -- Method on SettingNameException: SettingNameException (const Setting &SETTING, const char *NAME)

     This method constructs a SettingNameExcpetion object for the given SETTING and member name NAME.

A ParseException is thrown when a parse error occurs while reading a configuration from a stream.

 -- Method on ParseException: ParseException (const char *FILE, int LINE, const char *ERROR)

     This method constructs a ParseException object with the given filename FILE, line number LINE, and error message ERROR.

A FileIOException is thrown when an I/O error occurs while reading/writing a configuration from/to a file.

SettingTypeException, SettingNotFoundException, and SettingNameException all extend the common base exception SettingException, which provides the following method:

 -- Method on SettingException: const char * getPath () const

     This method returns the path to the setting associated with the exception, or NULL if there is no applicable path.

The remainder of this chapter describes the methods for manipulating configurations and configuration settings.

 -- Method on Config: Config ()
 -- Method on Config: ~Config ()

     These methods create and destroy Config objects.

 -- Method on Config: void clear ()

     Since v1.7

     This method clears the configuration. All child settings of the root setting are recursively destroyed. All other attributes of the configuration are left unchanged.

 -- Method on Config: void read (FILE * STREAM)
 -- Method on Config: void write (FILE * STREAM) const

     The read() method reads and parses a configuration from the given STREAM. A ParseException is thrown if a parse error occurs.

     The write() method writes the configuration to the given STREAM.

 -- Method on Config: void readFile (const char * FILENAME)
 -- Method on Config: void readFile (const std::string &FILENAME)

     The readFile() method reads and parses a configuration from the file named FILENAME. A ParseException is thrown if a parse error occurs. A FileIOException is thrown if the file cannot be read.

 -- Method on Config: void writeFile (const char * FILENAME)
 -- Method on Config: void writeFile (const std::string &FILENAME)

     The writeFile() method writes the configuration to the file named FILENAME. A FileIOException is thrown if the file cannot be written.

 -- Method on Config: void readString (const char * STR)
 -- Method on Config: void readString (const std::string &STR)

     These methods read and parse a configuration from the string STR. A ParseException is thrown if a parse error occurs.

 -- Method on ParseException: const char * getError () const
 -- Method on ParseException: const char * getFile () const
 -- Method on ParseException: int getLine () const

     If a call to readFile(), readString(), or read() resulted in a ParseException, these methods can be called on the exception object to obtain the text, filename, and line number of the parse error. Storage for the strings returned by getError() and getFile() are managed by the library; the strings must not be freed by the caller.

 -- Method on Config: void setIncludeDir (const char *INCLUDEDIR)
 -- Method on Config: const char * getIncludeDir () const

     The setIncludeDir() method specifies the include directory, INCLUDEDIR, relative to which the files specified in @include directives will be located for the configuration. By default, there is no include directory, and all include files are expected to be relative to the current working directory. If INCLUDEDIR is NULL, the default behavior is reinstated.

     For example, if the include directory is set to /usr/local/etc, the include directive @include "configs/extra.cfg" would include the file /usr/local/etc/configs/extra.cfg.

     getIncludeDir() returns the current include directory for the configuration, or NULL if none is set.

 -- Method on Config: virtual const char ** evaluateIncludePath (const char * PATH, const char ** ERROR)

     Since v1.7

     This method is called to evaluate the path of an @include directive. The PATH is the literal path argument of the directive. The method may be overridden in a subclass to perform tasks like wildcard expansion and variable substitution.

     On success, the method should return a NULL-terminated array of paths. Any relative paths must be relative to the program's current working directory. The contents of these files will be inlined at the point of inclusion, in the order that the paths appear in the array. Both the array and its elements should be heap allocated; the library will take ownership of and eventually free the strings in the array and the array itself.

     On failure, the function should return NULL and set *ERROR to a static error string which should be used as the parse error for the configuration; the library does not take ownership of or free this string.

     The default implementation simply returns a NULL-terminated array containing either a copy of PATH if it's an absolute path, or a concatenation of the include directory and PATH if it's a relative path.

     For more information see config_set_include_func() above.

 -- Method on Config: int getOptions () const
 -- Method on Config: void setOptions (int OPTIONS)

     These methods get and set the options for the configuration. The options affect how configurations are read and written. The parameter OPTIONS should be a bitwise-OR of the following CONFIG::OPTION enumeration values:

     Config::OptionAutoConvert
          Turning this option on enables number auto-conversion for the configuration. When this feature is enabled, an attempt to retrieve a floating point setting's value into an integer (or vice versa), or store an integer to a floating point setting's value (or vice versa) will cause the library to silently perform the necessary conversion (possibly leading to loss of data), rather than reporting failure. By default this option is turned off.

     Config::OptionSemicolonSeparators
          This option controls whether a semicolon (`;') is output after each setting when the configuration is written to a file or stream. (The semicolon separators are optional in the configuration syntax.) By default this option is turned on.

     Config::OptionColonAssignmentForGroups
          This option controls whether a colon (`:') is output between each group setting's name and its value when the configuration is written to a file or stream. If the option is turned off, an equals sign (`=') is output instead. (These tokens are interchangeable in the configuration syntax.) By default this option is turned on.

     Config::OptionColonAssignmentForNonGroups
          This option controls whether a colon (`:') is output between each non-group setting's name and its value when the configuration is written to a file or stream. If the option is turned off, an equals sign (`=') is output instead. (These tokens are interchangeable in the configuration syntax.) By default this option is turned off.

     Config::OptionOpenBraceOnSeparateLine
          This option controls whether an open brace (`{') will be written on its own line when the configuration is written to a file or stream. If the option is turned off, the brace will be written at the end of the previous line. By default this option is turned on.

     Config::OptionAllowScientificNotation
          (Since v1.7) This option controls whether scientific notation may be used as appropriate when writing floating point values (corresponding to printf() %g format) or should never be used (corresponding to printf() %f format). By default this option is turned off.

     Config::OptionFsync
          (Since v1.7.1) This option controls whether the writeFile() method performs an fsync operation after writing the configuration and before closing the file. By default this option is turned off.

     Config::OptionAllowOverrides
          (Since v1.7.3) This option controls whether duplicate settings override previous settings with the same name. If this option is turned off, duplicate settings are rejected. By default this option is turned off.

 -- Method on Config: bool getOption (Config::Option OPTION) const
 -- Method on Config: void setOption (Config::Option OPTION, bool FLAG)

     Since v1.7

     These methods get and set the option OPTION for the configuration. The option is enabled if FLAG is true and disabled if it is false.

     See setOptions() above for the list of available options.

 -- Method on Config: bool getAutoConvert () const
 -- Method on Config: void setAutoConvert (bool FLAG)

     These methods get and set the OptionAutoConvert option. They are obsoleted by the setOption() and getOption() methods described above.

 -- Method on Config: Setting::Format getDefaultFormat () const
 -- Method on Config: void setDefaultFormat (Setting::Format FORMAT)

     These methods get and set the default external format for settings in the configuration. If a non-default format has not been set for a setting with Setting::setFormat(), this configuration-wide default format will be used instead when that setting is written to a file or stream.

 -- Method on Config: unsigned short getTabWidth () const
 -- Method on Config: void setTabWidth (unsigned short WIDTH)

     These methods get and set the tab width for the configuration. The tab width affects the formatting of the configuration when it is written to a file or stream: each level of nesting is indented by WIDTH spaces, or by a single tab character if WIDTH is 0. The tab width has no effect on parsing.

     Valid tab widths range from 0 to 15. The default tab width is 2.

 -- Method on Config: unsigned short getFloatPrecision () const
 -- Method on Config: void setFloatPrecision (unsigned short WIDTH)

     These methods get and set the float precision for the configuration. This parameter influences the formatting of floating point settings in the configuration when it is written to a file or stream. Float precision has no effect on parsing.

     Valid precisions range from 0 to about 15 (implementation dependent), though the library will accept and store values up to 255.

 -- Method on Config: Setting & getRoot () const

     This method returns the root setting for the configuration, which is a group.

 -- Method on Config: Setting & lookup (const std::string &PATH) const
 -- Method on Config: Setting & lookup (const char * PATH) const

     These methods locate the setting specified by the path PATH. If the requested setting is not found, a SettingNotFoundException is thrown.

 -- Method on Config: bool exists (const std::string &PATH) const
 -- Method on Config: bool exists (const char *PATH) const

     These methods test if a setting with the given PATH exists in the configuration. They return true if the setting exists, and false otherwise. These methods do not throw exceptions.

 -- Method on Config: bool lookupValue (const char *PATH, bool &VALUE) const
 -- Method on Config: bool lookupValue (const std::string &PATH, bool &VALUE) const

 -- Method on Config: bool lookupValue (const char *PATH, int &VALUE) const
 -- Method on Config: bool lookupValue (const std::string &PATH, int &VALUE) const

 -- Method on Config: bool lookupValue (const char *PATH, unsigned int &VALUE) const
 -- Method on Config: bool lookupValue (const std::string &PATH, unsigned int &VALUE) const

 -- Method on Config: bool lookupValue (const char *PATH, long long &VALUE) const
 -- Method on Config: bool lookupValue (const std::string &PATH, long long &VALUE) const

 -- Method on Config: bool lookupValue (const char *PATH, float &VALUE) const
 -- Method on Config: bool lookupValue (const std::string &PATH, float &VALUE) const

 -- Method on Config: bool lookupValue (const char *PATH, double &VALUE) const
 -- Method on Config: bool lookupValue (const std::string &PATH, double &VALUE) const

 -- Method on Config: bool lookupValue (const char *PATH, const char *&VALUE) const
 -- Method on Config: bool lookupValue (const std::string &PATH, const char *&VALUE) const

 -- Method on Config: bool lookupValue (const char *PATH, std::string &VALUE) const
 -- Method on Config: bool lookupValue (const std::string &PATH, std::string &VALUE) const

     These are convenience methods for looking up the value of a setting with the given PATH. If the setting is found and is of an appropriate type, the value is stored in VALUE and the method returns true. Otherwise, VALUE is left unmodified and the method returns false. These methods do not throw exceptions.

     Storage for const char * values is managed by the library and released automatically when the setting is destroyed or when its value is changed; the string must not be freed by the caller. For safety and convenience, always assigning string values to a std::string is suggested.

     Since these methods have boolean return values and do not throw exceptions, they can be used within boolean logic expressions. The following example presents a concise way to look up three values at once and perform error handling if any of them are not found or are of the wrong type:

          int var1;
          double var2;
          const char *var3;

          if(config.lookupValue("values.var1", var1)
             && config.lookupValue("values.var2", var2)
             && config.lookupValue("values.var3", var3))
          {
            // use var1, var2, var3
          }
          else
          {
            // error handling here
          }

     This approach also takes advantage of the short-circuit evaluation rules of C++, e.g., if the first lookup fails (returning false), the remaining lookups are skipped entirely.

 -- Method on Setting: operator bool () const
 -- Method on Setting: operator int () const
 -- Method on Setting: operator unsigned int () const
 -- Method on Setting: operator long () const
 -- Method on Setting: operator unsigned long () const
 -- Method on Setting: operator long long () const
 -- Method on Setting: operator unsigned long long () const
 -- Method on Setting: operator float () const
 -- Method on Setting: operator double () const
 -- Method on Setting: operator const char * () const
 -- Method on Setting: operator std::string () const
 -- Method on Setting: const char * c_str () const

     These cast operators allow a Setting object to be assigned to a variable of type bool if it is of type TypeBoolean; int, unsigned int; long long or unsigned long long if it is of type TypeInt64, float or double if it is of type TypeFloat; or const char * or std::string if it is of type TypeString.

     Values of type TypeInt or TypeInt64 may be assigned to variables of type long, or unsigned long, depending on the sizes of those types on the host system.

     Storage for const char * return values is managed by the library and released automatically when the setting is destroyed or when its value is changed; the string must not be freed by the caller. For safety and convenience, always assigning string return values to a std::string is suggested.

     The following examples demonstrate this usage:

          long width = config.lookup("application.window.size.w");

          bool splashScreen = config.lookup("application.splash_screen");

          std::string title = config.lookup("application.window.title");

     Note that certain conversions can lead to loss of precision or clipping of values, e.g., assigning a negative value to an unsigned int (in which case the value will be treated as 0), or a double-precision value to a float. The library does not treat these lossy conversions as errors.

     Perhaps surprisingly, the following code in particular will cause a compiler error:

          std::string title;
          .
          .
          .
          title = config.lookup("application.window.title");

     This is because the assignment operator of std::string is being invoked with a Setting & as an argument. The compiler is unable to make an implicit conversion because both the const char * and the std::string cast operators of Setting are equally appropriate. This is not a bug in libconfig; providing only the const char * cast operator would resolve this particular ambiguity, but would cause assignments to std::string like the one in the previous example to produce a compiler error. (To understand why, see section 11.4.1 of The C++ Programming Language.)

     The solution to this problem is to use an explicit conversion that avoids the construction of an intermediate std::string object, as follows:

          std::string title;
          .
          .
          .
          title = (const char *)config.lookup("application.window.title");

     Or, alternatively, use the c_str() method, which has the same effect:

          std::string title;
          .
          .
          .
          title = config.lookup("application.window.title").c_str();

     If the assignment is invalid due to a type mismatch, a SettingTypeException is thrown.

 -- Method on Setting: Setting & operator= (bool VALUE)
 -- Method on Setting: Setting & operator= (int VALUE)
 -- Method on Setting: Setting & operator= (long VALUE)
 -- Method on Setting: Setting & operator= (const long long &VALUE)
 -- Method on Setting: Setting & operator= (float VALUE)
 -- Method on Setting: Setting & operator= (const double &VALUE)
 -- Method on Setting: Setting & operator= (const char *VALUE)
 -- Method on Setting: Setting & operator= (const std::string &VALUE)

     These assignment operators allow values of type bool, int, long, long long, float, double, const char *, and std::string to be assigned to a setting. In the case of strings, the library makes a copy of the passed string VALUE, so it may be subsequently freed or modified by the caller without affecting the value of the setting.

     The following example code looks up a (presumably) integer setting and changes its value:

          Setting &setting = config.lookup("application.window.size.w");
          setting = 1024;

     If the assignment is invalid due to a type mismatch, a SettingTypeException is thrown.

 -- Method on Setting: Setting & operator[] (int INDEX) const
 -- Method on Setting: Setting & operator[] (const std::string &NAME) const
 -- Method on Setting: Setting & operator[] (const char *NAME) const

     A Setting object may be subscripted with an integer index INDEX if it is an array or list, or with either a string NAME or an integer index INDEX if it is a group. For example, the following code would produce the string Last Name when applied to the example configuration in Configuration Files.

          Setting& setting = config.lookup("application.misc");
          const char *s = setting["columns"][0];

     If the setting is not an array, list, or group, a SettingTypeException is thrown. If the subscript (INDEX or NAME) does not refer to a valid element, a SettingNotFoundException is thrown.

     Iterating over a group's child settings with an integer index will return the settings in the same order that they appear in the configuration.

 -- Method on Setting: Setting & lookup (const char * PATH) const
 -- Method on Setting: Setting & lookup (const std::string &PATH) const

     These methods locate a setting by a path PATH relative to this setting. If requested setting is not found, a SettingNotFoundException is thrown.

 -- Method on Setting: bool lookupValue (const char *NAME, bool &VALUE) const
 -- Method on Setting: bool lookupValue (const std::string &NAME, bool &VALUE) const

 -- Method on Setting: bool lookupValue (const char *NAME, int &VALUE) const
 -- Method on Setting: bool lookupValue (const std::string &NAME, int &VALUE) const

 -- Method on Setting: bool lookupValue (const char *NAME, unsigned int &VALUE) const
 -- Method on Setting: bool lookupValue (const std::string &NAME, unsigned int &VALUE) const

 -- Method on Setting: bool lookupValue (const char *NAME, long long &VALUE) const
 -- Method on Setting: bool lookupValue (const std::string &NAME, long long &VALUE) const

 -- Method on Setting: bool lookupValue (const char *NAME, unsigned long long &VALUE) const
 -- Method on Setting: bool lookupValue (const std::string &NAME, unsigned long long &VALUE) const

 -- Method on Setting: bool lookupValue (const char *NAME, float &VALUE) const
 -- Method on Setting: bool lookupValue (const std::string &NAME, float &VALUE) const

 -- Method on Setting: bool lookupValue (const char *NAME, double &VALUE) const
 -- Method on Setting: bool lookupValue (const std::string &NAME, double &VALUE) const

 -- Method on Setting: bool lookupValue (const char *NAME, const char *&VALUE) const
 -- Method on Setting: bool lookupValue (const std::string &NAME, const char *&VALUE) const

 -- Method on Setting: bool lookupValue (const char *NAME, std::string &VALUE) const
 -- Method on Setting: bool lookupValue (const std::string &NAME, std::string &VALUE) const

     These are convenience methods for looking up the value of a child setting with the given NAME. If the setting is found and is of an appropriate type, the value is stored in VALUE and the method returns true. Otherwise, VALUE is left unmodified and the method returns false. These methods do not throw exceptions.

     Storage for const char * values is managed by the library and released automatically when the setting is destroyed or when its value is changed; the string must not be freed by the caller. For safety and convenience, always assigning string values to a std::string is suggested.

     Since these methods have boolean return values and do not throw exceptions, they can be used within boolean logic expressions. The following example presents a concise way to look up three values at once and perform error handling if any of them are not found or are of the wrong type:

          int var1;
          double var2;
          const char *var3;

          if(setting.lookupValue("var1", var1)
             && setting.lookupValue("var2", var2)
             && setting.lookupValue("var3", var3))
          {
            // use var1, var2, var3
          }
          else
          {
            // error handling here
          }

     This approach also takes advantage of the short-circuit evaluation rules of C++, e.g., if the first lookup fails (returning false), the remaining lookups are skipped entirely.

 -- Method on Setting: Setting & add (const std::string &NAME, Setting::Type TYPE)
 -- Method on Setting: Setting & add (const char *NAME, Setting::Type TYPE)

     These methods add a new child setting with the given NAME and TYPE to the setting, which must be a group. They return a reference to the new setting. If the setting already has a child setting with the given name, or if the name is invalid, a SettingNameException is thrown. If the setting is not a group, a SettingTypeException is thrown.

     Once a setting has been created, neither its name nor type can be changed.

 -- Method on Setting: Setting & add (Setting::Type TYPE)

     This method adds a new element to the setting, which must be of type TypeArray or TypeList. If the setting is an array which currently has zero elements, the TYPE parameter (which must be TypeInt, TypeInt64, TypeFloat, TypeBool, or TypeString) determines the type for the array; otherwise it must match the type of the existing elements in the array.

     The method returns the new setting on success. If TYPE is a scalar type, the new setting will have a default value of 0, 0.0, false, or NULL, as appropriate.

     The method throws a SettingTypeException if the setting is not an array or list, or if TYPE is invalid.

 -- Method on Setting: void remove (const std::string &NAME)
 -- Method on Setting: void remove (const char *NAME)

     These methods remove the child setting with the given NAME from the setting, which must be a group. Any child settings of the removed setting are recursively destroyed as well.

     If the setting is not a group, a SettingTypeException is thrown.  If the setting does not have a child setting with the given name, a SettingNotFoundException is thrown.

 -- Method on Setting: void remove (unsigned int INDEX)

     This method removes the child setting at the given index INDEX from the setting, which must be a group, list, or array. Any child settings of the removed setting are recursively destroyed as well.

     If the setting is not a group, list, or array, a SettingTypeException is thrown.  If INDEX is out of range, a SettingNotFoundException is thrown.

 -- Method on Setting: const char * getName () const

     This method returns the name of the setting, or NULL if the setting has no name. Storage for the returned string is managed by the library and released automatically when the setting is destroyed; the string must not be freed by the caller. For safety and convenience, consider assigning the return value to a std::string.

 -- Method on Setting: std::string getPath () const

     This method returns the complete dot-separated path to the setting. Settings which do not have a name (list and array elements) are represented by their index in square brackets.

 -- Method on Setting: Setting & getParent () const

     This method returns the parent setting of the setting. If the setting is the root setting, a SettingNotFoundException is thrown.

 -- Method on Setting: bool isRoot () const

     This method returns true if the setting is the root setting, and false otherwise.

 -- Method on Setting: int getIndex () const

     This method returns the index of the setting within its parent setting. When applied to the root setting, this method returns -1.

 -- Method on Setting: Setting::Type getType () const

     This method returns the type of the setting. The Setting::Type enumeration consists of the following constants: TypeInt, TypeInt64, TypeFloat, TypeString, TypeBoolean, TypeArray, TypeList, and TypeGroup.

 -- Method on Setting: Setting::Format getFormat () const
 -- Method on Setting: void setFormat (Setting::Format FORMAT)

     These methods get and set the external format for the setting.

     The SETTING::FORMAT enumeration consists of the following constants: FormatDefault and FormatHex. All settings support the FormatDefault format. The FormatHex format specifies hexadecimal formatting for integer values, and hence only applies to settings of type TypeInt and TypeInt64. If FORMAT is invalid for the given setting, it is ignored.

 -- Method on Setting: bool exists (const std::string &NAME) const
 -- Method on Setting: bool exists (const char *NAME) const

     These methods test if the setting has a child setting with the given NAME. They return true if the setting exists, and false otherwise. These methods do not throw exceptions.

 -- Method on Setting: iterator begin ()
 -- Method on Setting: iterator end ()
 -- Method on Setting: const_iterator begin ()
 -- Method on Setting: const_iterator end ()

     These methods return STL-style iterators that can be used to enumerate the child settings of a given setting. If the setting is not an array, list, or group, they throw a SettingTypeException.

 -- Method on Setting: int getLength () const

     This method returns the number of settings in a group, or the number of elements in a list or array. For other types of settings, it returns 0.

 -- Method on Setting: bool isGroup () const
 -- Method on Setting: bool isArray () const
 -- Method on Setting: bool isList () const

     These convenience methods test if a setting is of a given type.

 -- Method on Setting: bool isAggregate () const
 -- Method on Setting: bool isScalar () const
 -- Method on Setting: bool isNumber () const
 -- Method on Setting: bool isString () const

     These convenience methods test if a setting is of an aggregate type (a group, array, or list), of a scalar type (integer, 64-bit integer, floating point, boolean, or string), of a number (integer, 64-bit integer, or floating point), and of a string respectively.

 -- Method on Setting: const char * getSourceFile () const

     This method returns the name of the file from which the setting was read, or NULL if the setting was not read from a file. This information is useful for reporting application-level errors. Storage for the returned string is managed by the library and released automatically when the configuration is destroyed; the string must not be freed by the caller.

 -- Method on Setting: unsigned int getSourceLine () const

     This method returns the line number of the configuration file or stream at which the setting SETTING was read, or 0 if no line number is available. This information is useful for reporting application-level errors.

Example Programs
****************

Practical example programs that illustrate how to use libconfig from both C and C++ are included in the examples subdirectory of the distribution. These examples include:

examples/c/example1.c
     An example C program that reads a configuration from an existing file example.cfg (also located in examples/c) and displays some of its contents.

examples/c++/example1.cpp
     The C++ equivalent of example1.c.

examples/c/example2.c
     An example C program that reads a configuration from an existing file example.cfg (also located in examples/c), adds new settings to the configuration, and writes the updated configuration to another file.

examples/c++/example2.cpp
     The C++ equivalent of example2.c

examples/c/example3.c
     An example C program that constructs a new configuration in memory and writes it to a file.

examples/c++/example3.cpp
     The C++ equivalent of example3.c

examples/c/example4.c
     An example C program that uses a custom include function for processing wildcard includes. Note that this code will not compile on Windows.

Other Bindings and Implementations
**********************************

Various open-source libraries have been written that provide access to libconfig-style configuration files from other programming languages. Some of these libraries are wrappers which add new language bindings for libconfig while others are syntax-compatible reimplementations in other languages.

Here is a list of some of these implementations.

Bourne Shell
============

Łukasz A. Grabowski's ls-config provides a means to read and write values in libconfig configuration files from Bourne shell scripts. The implementation is included in the libconfig git repository at https://github.com/hyperrealm/libconfig, in the contrib/ls-config subdirectory.

D
=

Remi Thebault's libconfig-d is a port of libconfig to the D programming language. It may be found at https://code.dlang.org/packages/libconfig-d.

Haskell
=======

Matthew Peddie's libconfig provides Haskell bindings to libconfig. It may be found at https://hackage.haskell.org/package/libconfig-0.3.0.0.

Java
====

Andrey V. Pleskach has a pure-Java implementation of libconfig. It may be found on github at https://github.com/willyborankin/libconfig.

Lisp
====

Oleg Shalaev's cl-libconfig provides Common Lisp bindings for libconfig. It may be found on github at https://github.com/chalaev/cl-libconfig.

Perl
====

The Conf::Libconfig module provides Perl bindings for libconfig. It may be found on CPAN at http://search.cpan.org/~cnangel/Conf-Libconfig-0.05/ or on github at https://github.com/cnangel/Conf-Libconfig.

Python
======

Heiner Tholen's pylibconfig2 is a Python library that is syntax-compatible with libconfig. It may be found at https://pypi.python.org/pypi/pylibconfig2/0.1.2.

Christian Aichinger's libconf is another pure-Python implementation with a more permissive license. It may be found at https://pypi.python.org/pypi/libconf or on github at https://github.com/Grk0/python-libconf.

The python-libconfig wrapper provides Python bindings to libconfig. It may be found on github at https://github.com/cnangel/python-libconfig/.

Ruby
====

Christopher Mark Gore's ruby-libconfig is a Ruby library that provides Ruby bindings for libconfig. It may be found at https://rubygems.org/gems/libconfig or on github at https://github.com/cgore/ruby-libconfig.

There is also another Ruby wrapper, libconfig-ruby, that is included in the libconfig git repository at https://github.com/hyperrealm/libconfig, in the contrib/libconfig-ruby subdirectory.

License
*******

     [file LGPL.texi not included]

Configuration File Grammar
**************************

Below is the BNF grammar for configuration files. Comments and include directives are not part of the grammar, so they are not included here.

     <configuration> ::=
           <setting-list>
         | <empty>

     <setting-list> ::=
           <setting>
         | <setting-list> <setting>

     <setting> ::=
           <name> ( ":" | "=" ) <value> ( ";" | "," | <empty> )

     <value> ::=
           <scalar-value>
         | <array>
         | <list>
         | <group>

     <value-list> ::=
           <value>
         | <value-list> "," <value>
         | <value-list> ","

     <scalar-value> ::=
           <boolean>
         | <integer>
         | <integer64>
         | <hex>
         | <hex64>
         | <float>
         | <string>

     <scalar-value-list> ::=
           <scalar-value>
         | <scalar-value-list> "," <scalar-value>
         | <scalar-value-list> ","

     <array> ::=
           "[" ( <scalar-value-list> | <empty> ) "]"

     <list> ::=
           "(" ( <value-list> | <empty> ) ")"

     <group> ::=
           "{" ( <setting-list> | <empty> ) "}"

     <empty> ::=

Terminals are defined below as regular expressions:

<boolean>
([Tt][Rr][Uu][Ee])|([Ff][Aa][Ll][Ss][Ee])
<string>
\"([^\"\\]|\\.)*\"
<name>
[A-Za-z\*][-A-Za-z0-9_\*]*
<integer>
[-+]?[0-9]+
<integer64>
[-+]?[0-9]+L(L)?
<hex>
0[Xx][0-9A-Fa-f]+
<hex64>
0[Xx][0-9A-Fa-f]+(L(L)?)?
<float>
([-+]?([0-9]*)?\.[0-9]*([eE][-+]?[0-9]+)?)|([-+]([0-9]+)(\.[0-9]*)?[eE][-+]?[0-9]+)

Note that adjacent strings are automatically concatenated. Non-printable characters can be represented within strings using a sequence \xx, representing the ASCII value as two hex digits.