ALib C++ Library
Library Version: 2402 R1
Documentation generated by doxygen
Loading...
Searching...
No Matches
IniFile Class Reference

Description:


Specialization of class InMemoryPlugin, which reads and writes a simple configuration file consisting of sections containing key/value pairs.

This class is provided for the case that no other configuration mechanism is available. In general, application specific configuration mechanisms already exist in other libraries used. Those should be adopted by creating a lean interface plug-in for ALib .

Some remarks on the functionality and supported format:

  • Comments
    • Comment lines at the beginning of the file are associated with the file and are written back. Such comment block is stopped with a single blank line.
    • Lines that start (apart from whitespace) with either a double slash "//", a sharp sign '#' or a semicolon ';' are comment lines.
    • Comment lines that are added to variables in the software are using the symbol defined in filed DefaultCommentPrefix, which defaults to '#'. If this is changed in the file, such changes are preserved.
    • Comment lines before sections and variables are associated with the respective objects and are not overwritten by comments set in the code. However, variables without comments which are overwritten in code including comments, get such comment appended.
    • Comments can not reside in the same line together with section names or variables.
    • Commented variables receive a blank line before the comment on writing.
    • Commented Sections receive two blank lines before the comment on writing. One if they are not commented.
    • Before a file is written, new sections (those that have been created during the use of the object) can be identified by a nulled comment variable, while the string is not nulled (but maybe empty) when read from the file. This information may be used to add comments to new sections, prior to writing the file, while preventing to restore comments that have been deleted by the user.
  • Sections:
    • Sections names are enclosed by brackets '[' and ']'.
    • Section names can be repeated. In this case the corresponding section is continued. When the file is written, the sections are merged. Otherwise the order of sections and the variables within the section is kept intact on writing.
  • Variables
    • Variable names and their values are separated by an equal sign '='.
    • New variables inserted are formatted according to other variables found. E.g. the equal sign of all variables within a section are aligned on the same column.
    • Formats of variables added or changed by the user are kept intact, as long as the software does not store a value.
  • Continued Lines:
    • Variables definition are being continued (values are concatenated) if the line ends with a backslash '\'.
    • Comment lines in-between continued lines are recognized as such. To continue a variable after a 'continued' comment line, the comment line needs to end with a backslash '\'.
    • Variables with multiple values created (or modified) in the software, are written in continued lines, with each line showing one value, ending with the variables' delimiter character and a trailing '\'.
    • Comment lines within Variables defined in multiple lines are removed when a variable is written back.
  • Escaping values
    • Spaces ' ' and tabulators '\t' are ignored at the start and end of each line and before and after the equal sign '='.
    • Consequently, whitespaces at the start or end of a value either need to be escaped using '\ ' or the whole value has to be surrounded by double quotes ".
    • Values added or modified by the software that contain spaces at the start or end are surrounded by double quotes (instead of escaping them)
    • Double quotes in values are always escaped when writing values and have to be escaped when editing the file.
    • Values may consist of a list of double quoted values. Whitespaces between such values are ignored. Consequently, long strings may be enclosed in double quotes and continued in the next line when the line ends with a backslash '\'.
    • Almost any character can be escaped. E.g "\\a" is read as 'a'.
    • On writing only non-printable characters and double quotation marks are escaped.
  • Other remarks
    • Sequences of blank lines are reduced to one blank line, when writing the file.
    • Erroneous lines are ignored and not written back. Line numbers with erroneous lines are collected in field LinesWithReadErrors.

Reference Documentation

Exceptions
alib::config::Exceptions::ErrorOpeningFile
alib::config::Exceptions::ErrorWritingFile

Definition at line 100 of file inifile.hpp.

#include <inifile.hpp>

Inheritance diagram for IniFile:
[legend]
Collaboration diagram for IniFile:
[legend]

Public Static Field Index:

static String DefaultFileExtension = A_CHAR(".ini")
 

Public Static Method Index:

static ALIB_API void AddResourcedSectionComments (Configuration &config, ResourcePool &resourcePool, const NString &resourceCategory, const NString &resourceNamePrefix)
 

Public Field Index:

bool AutoSave = false
 
String DefaultCommentPrefix =A_CHAR("# ")
 
AString FileComments
 
AString FileName
 
bool FormatIncludeDelimInAttrAlignment = false
 
bool FormatSpaceAfterDelim = true
 
bool FormatSpaceBeforeDelim = false
 
List< integerLinesWithReadErrors
 
int LineWidth = 100
 
- Public Field Index: inherited from ConfigurationPlugin
XTernalizerStringConverter
 

Public Method Index:

ALIB_API IniFile (const String &filePathAndName=nullptr)
 
virtual ~IniFile () override
 
virtual ALIB_API void Clear () override
 
virtual ALIB_API void FromVariable (Entry &entry, Variable &variable) const override
 
virtual ALIB_API bool Load (Variable &variable, bool searchOnly=false) override
 
virtual String Name () const override
 
ALIB_API void ReadFile ()
 
virtual bool Store (Variable &variable) override
 
virtual ALIB_API void ToVariable (Entry &entry, Variable &variable) const override
 
ALIB_API void WriteFile ()
 
- Public Method Index: inherited from InMemoryPlugin
ALIB_API InMemoryPlugin (String pName, MonoAllocator *externalMA=nullptr)
 
virtual ALIB_API ~InMemoryPlugin () override
 
virtual ALIB_API IteratorGetIterator (const String &sectionName) override
 
EntrySearchEntry (const String &section, const String &name)
 
EntrySearchEntry (Section *section, const String &name)
 
ALIB_API std::pair< Section *, bool > SearchOrCreateSection (const String &sectionName)
 
ALIB_API const SectionSearchSection (const String &sectionName)
 
const List< Section > & Sections () const
 
virtual bool Store (Variable &variable, const String &externalizedValue)
 
- Public Method Index: inherited from ConfigurationPlugin
virtual ~ConfigurationPlugin ()
 

Field Details:

◆ AutoSave

bool AutoSave = false

If this is set to true, any variable change will lead to writing the file immediately by invoking WriteFile. Defaults to false

Definition at line 109 of file inifile.hpp.

◆ DefaultCommentPrefix

String DefaultCommentPrefix =A_CHAR("# ")

The prefix that is used for comment lines of sections or variables that have been added 'in code' (variables that have not been read from the file). Comments that were read from the file preserve their prefix. If comments including one of the valid prefixes are added to a variable or section 'in code', such prefix is preserved.

Definition at line 136 of file inifile.hpp.

◆ DefaultFileExtension

String DefaultFileExtension = A_CHAR(".ini")
static

The standard file extension used for ALib configuration files. Defaults to ".ini".

Definition at line 113 of file inifile.hpp.

◆ FileComments

AString FileComments

The file header which will be written out as a comment lines with "# " prefixes

Definition at line 120 of file inifile.hpp.

◆ FileName

AString FileName

The file name. This might include a path or not. Should be set properly before the file is read.

Definition at line 117 of file inifile.hpp.

◆ FormatIncludeDelimInAttrAlignment

bool FormatIncludeDelimInAttrAlignment = false

Denotes whether the spaces that are inserted when aligning attributes are located before or behind the delimiter.

Definition at line 147 of file inifile.hpp.

◆ FormatSpaceAfterDelim

bool FormatSpaceAfterDelim = true

Denotes if a space should be written after a delimiter. (Applies only to single line mode of writing attributes.)

Definition at line 143 of file inifile.hpp.

◆ FormatSpaceBeforeDelim

bool FormatSpaceBeforeDelim = false

Denotes if a space should be written before a delimiter.

Definition at line 139 of file inifile.hpp.

◆ LinesWithReadErrors

List<integer> LinesWithReadErrors

Is cleared and filled with faulty line numbers when reading the file. (E.g. when a line is no section and no comment but still has no equal sign ('=').

Definition at line 128 of file inifile.hpp.

◆ LineWidth

int LineWidth = 100

The desired maximum width of the INI-file. Defaults to 100. This value is used with utility method AddResourcedSectionComments

Definition at line 124 of file inifile.hpp.

Constructor(s) / Destructor Details::

◆ IniFile()

IniFile ( const String & filePathAndName = nullptr)

Constructs an instance of this class and reads the file. If no file name is given, the file name is set to the process name with extension found in public static field DefaultFileExtension.

If the given file name equals '*', no file is read and field AutoSave is set to false.

If the given name does not start with either a path separation character or a dot character ., then Directory::SpecialFolder::HomeConfig is prepended to the given name.

Parameters
filePathAndNameThe name (and path) of the file to read and write. Provide "*" to suppress reading a file. Defaults to nullptr.

Definition at line 161 of file inifile.cpp.

Here is the call graph for this function:

◆ ~IniFile()

virtual ~IniFile ( )
inlineoverridevirtual

Virtual Destructor.

Definition at line 174 of file inifile.hpp.

Method Details:

◆ AddResourcedSectionComments()

void AddResourcedSectionComments ( Configuration & config,
ResourcePool & resourcePool,
const NString & resourceCategory,
const NString & resourceNamePrefix )
static

This is a static utility function that reads section comments from externalized string resources.

All sections of all INI-files of given config are processed, but resourced comments are only added in the case that a section's comment string is nulled. This is not the case if a section was read from from an INI-file, as even if no comments are given, the field is empty, but not nulled. In other words, only sections that have been programatically added during the run of a software are changed
This approach allows a user to remove the comments, without the software restoring them.

The resource names are assembled from given resourceNamePrefix and the section name. The resource strings found are processed using method Paragraphs.AddMarked . This allows to use text macros like '@HL' to format the text.

This method is best be invoked in phase ShutdownPhases::Announce of method Camp::shutdown .

See also
Field LineWidth, which is respected when formatting comment lines.
Parameters
configThe configuration that is searched for INI-file plug-ins.
resourcePoolThe resource pool to use.
resourceCategoryThe category of the resourced comments.
resourceNamePrefixA prefix of the resource name.

Definition at line 616 of file inifile.cpp.

Here is the call graph for this function:

◆ Clear()

void Clear ( )
overridevirtual

Clears all configuration data.

Reimplemented from InMemoryPlugin.

Definition at line 203 of file inifile.cpp.

Here is the call graph for this function:

◆ FromVariable()

void FromVariable ( Entry & entry,
Variable & variable ) const
overridevirtual

Overrides default method. Clears the raw value, and calls base method.

Parameters
entryThe entry to convert.
variableThe variable to fill with our values.

Reimplemented from InMemoryPlugin.

Definition at line 151 of file inifile.cpp.

Here is the call graph for this function:

◆ Load()

bool Load ( Variable & variable,
bool searchOnly = false )
overridevirtual

Searches the variable in our storage.

Parameters
variableThe variable to retrieve.
searchOnlyIf true, the variable is not read. Defaults to false.
Returns
true if variable was found, false if not.

Reimplemented from InMemoryPlugin.

Definition at line 445 of file inmemoryplugin.cpp.

◆ Name()

virtual String Name ( ) const
inlineoverridevirtual

Return the plug-in name, in this case, the file name.

Returns
The name of the plug-in.

Reimplemented from InMemoryPlugin.

Definition at line 250 of file inifile.hpp.

◆ ReadFile()

void ReadFile ( )

Clears all configuration data and reads the file. It might happen that lines are ignored or otherwise marked as faulty. All numbers of such lines get collected in field LinesWithReadErrors.

Exceptions
Exception(config::Exceptions::ErrorOpeningFile ).

Definition at line 225 of file inifile.cpp.

Here is the call graph for this function:

◆ Store()

virtual bool Store ( Variable & variable)
inlineoverridevirtual

Creates or replaces existing variable in our storage. If AutoSave is set, the file is written

Parameters
variableThe variable to retrieve.
Returns
true if the variable was written, false if not. The latter might only happen if the variable given was illegal, e.g. empty name.

Reimplemented from InMemoryPlugin.

Definition at line 263 of file inifile.hpp.

Here is the call graph for this function:

◆ ToVariable()

void ToVariable ( Entry & entry,
Variable & variable ) const
overridevirtual

Overrides default method. If we have not parsed the INI file's text value, yet, we do this now.

Parameters
entryThe entry to convert.
variableThe variable to fill with our values.

Reimplemented from InMemoryPlugin.

Definition at line 60 of file inifile.cpp.

Here is the call graph for this function:

◆ writeComments()

void writeComments ( strings::compatibility::std::StringWriter & os,
const AString & comments )
protected

Writes a list of comments to the file. Comment lines are started with '#'.

Parameters
osThe encapsulated output stream to write to.
commentsThe comment lines for the section.

Definition at line 363 of file inifile.cpp.

Here is the call graph for this function:

◆ WriteFile()

void WriteFile ( )

Write all configuration data into the file.

Exceptions
Exception(config::Exceptions::ErrorOpeningFile ).

Definition at line 400 of file inifile.cpp.

Here is the call graph for this function:

The documentation for this class was generated from the following files: