- Main Page
- Classes
- Files

- File List
- File Members

# ConfigFile.h

Go to the documentation of this file.

    00001 // ConfigFile.h
    00002 // Class for reading named values from configuration files
    00003 // Richard J. Wagner  v2.1  24 May 2004  wagnerr@umich.edu
    00004
    00005 // Copyright (c) 2004 Richard J. Wagner
    00006 //
    00007 // Permission is hereby granted, free of charge, to any person obtaining a copy
    00008 // of this software and associated documentation files (the "Software"), to
    00009 // deal in the Software without restriction, including without limitation the
    00010 // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
    00011 // sell copies of the Software, and to permit persons to whom the Software is
    00012 // furnished to do so, subject to the following conditions:
    00013 //
    00014 // The above copyright notice and this permission notice shall be included in
    00015 // all copies or substantial portions of the Software.
    00016 //
    00017 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    00018 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    00019 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    00020 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    00021 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
    00022 // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
    00023 // IN THE SOFTWARE.
    00024
    00025 // Typical usage
    00026 // -------------
    00027 //
    00028 // Given a configuration file "settings.inp":
    00029 //   atoms  = 25
    00030 //   length = 8.0  # nanometers
    00031 //   name = Reece Surcher
    00032 //
    00033 // Named values are read in various ways, with or without default values:
    00034 //   ConfigFile config( "settings.inp" );
    00035 //   int atoms = config.read<int>( "atoms" );
    00036 //   double length = config.read( "length", 10.0 );
    00037 //   string author, title;
    00038 //   config.readInto( author, "name" );
    00039 //   config.readInto( title, "title", string("Untitled") );
    00040 //
    00041 // See file example.cpp for more examples.
    00042
    00043 #ifndef CONFIGFILE_H
    00044 #define CONFIGFILE_H
    00045
    00046 #include <string>
    00047 #include <map>
    00048 #include <iostream>
    00049 #include <fstream>
    00050 #include <sstream>
    00051
    00052 using std::string;
    00053
    00054 class ConfigFile {
    00055 // Data
    00056 protected:
    00057         string myDelimiter;  // separator between key and value
    00058         string myComment;    // separator between value and comments
    00059         string mySentry;     // optional string to signal end of file
    00060         std::map<string,string> myContents;  // extracted keys and values
    00061
    00062         typedef std::map<string,string>::iterator mapi;
    00063         typedef std::map<string,string>::const_iterator mapci;
    00064
    00065 // Methods
    00066 public:
    00067         ConfigFile( string filename,
    00068                     string delimiter = "=",
    00069                     string comment = "#",
    00070                                 string sentry = "EndConfigFile" );
    00071         ConfigFile();
    00072
    00073         // Search for key and read value or optional default value
    00074         template<class T> T read( const string& key ) const;  // call as read<T>
    00075         template<class T> T read( const string& key, const T& value ) const;
    00076         template<class T> bool readInto( T& var, const string& key ) const;
    00077         template<class T>
    00078         bool readInto( T& var, const string& key, const T& value ) const;
    00079
    00080         // Modify keys and values
    00081         template<class T> void add( string key, const T& value );
    00082         void remove( const string& key );
    00083
    00084         // Check whether key exists in configuration
    00085         bool keyExists( const string& key ) const;
    00086
    00087         // Check or change configuration syntax
    00088         string getDelimiter() const { return myDelimiter; }
    00089         string getComment() const { return myComment; }
    00090         string getSentry() const { return mySentry; }
    00091         string setDelimiter( const string& s )
    00092                 { string old = myDelimiter;  myDelimiter = s;  return old; }
    00093         string setComment( const string& s )
    00094                 { string old = myComment;  myComment = s;  return old; }
    00095
    00096         // Write or read configuration
    00097         friend std::ostream& operator<<( std::ostream& os, const ConfigFile& cf );
    00098         friend std::istream& operator>>( std::istream& is, ConfigFile& cf );
    00099
    00100 protected:
    00101         template<class T> static string T_as_string( const T& t );
    00102         template<class T> static T string_as_T( const string& s );
    00103         static void trim( string& s );
    00104
    00105
    00106 // Exception types
    00107 public:
    00108         struct file_not_found {
    00109                 string filename;
    00110                 file_not_found( const string& filename_ = string() )
    00111                         : filename(filename_) {} };
    00112         struct key_not_found {  // thrown only by T read(key) variant of read()
    00113                 string key;
    00114                 key_not_found( const string& key_ = string() )
    00115                         : key(key_) {} };
    00116 };
    00117
    00118
    00119 /* static */
    00120 template<class T>
    00121 string ConfigFile::T_as_string( const T& t )
    00122 {
    00123         // Convert from a T to a string
    00124         // Type T must support << operator
    00125         std::ostringstream ost;
    00126         ost << t;
    00127         return ost.str();
    00128 }
    00129
    00130
    00131 /* static */
    00132 template<class T>
    00133 T ConfigFile::string_as_T( const string& s )
    00134 {
    00135         // Convert from a string to a T
    00136         // Type T must support >> operator
    00137         T t;
    00138         std::istringstream ist(s);
    00139         ist >> t;
    00140         return t;
    00141 }
    00142
    00143
    00144 /* static */
    00145 template<>
    00146 inline string ConfigFile::string_as_T<string>( const string& s )
    00147 {
    00148         // Convert from a string to a string
    00149         // In other words, do nothing
    00150         return s;
    00151 }
    00152
    00153
    00154 /* static */
    00155 template<>
    00156 inline bool ConfigFile::string_as_T<bool>( const string& s )
    00157 {
    00158         // Convert from a string to a bool
    00159         // Interpret "false", "F", "no", "n", "0" as false
    00160         // Interpret "true", "T", "yes", "y", "1", "-1", or anything else as true
    00161         bool b = true;
    00162         string sup = s;
    00163         for( string::iterator p = sup.begin(); p != sup.end(); ++p )
    00164                 *p = toupper(*p);  // make string all caps
    00165         if( sup==string("FALSE") || sup==string("F") ||
    00166             sup==string("NO") || sup==string("N") ||
    00167             sup==string("0") || sup==string("NONE") )
    00168                 b = false;
    00169         return b;
    00170 }
    00171
    00172
    00173 template<class T>
    00174 T ConfigFile::read( const string& key ) const
    00175 {
    00176         // Read the value corresponding to key
    00177         mapci p = myContents.find(key);
    00178         if( p == myContents.end() ) throw key_not_found(key);
    00179         return string_as_T<T>( p->second );
    00180 }
    00181
    00182
    00183 template<class T>
    00184 T ConfigFile::read( const string& key, const T& value ) const
    00185 {
    00186         // Return the value corresponding to key or given default value
    00187         // if key is not found
    00188         mapci p = myContents.find(key);
    00189         if( p == myContents.end() ) return value;
    00190         return string_as_T<T>( p->second );
    00191 }
    00192
    00193
    00194 template<class T>
    00195 bool ConfigFile::readInto( T& var, const string& key ) const
    00196 {
    00197         // Get the value corresponding to key and store in var
    00198         // Return true if key is found
    00199         // Otherwise leave var untouched
    00200         mapci p = myContents.find(key);
    00201         bool found = ( p != myContents.end() );
    00202         if( found ) var = string_as_T<T>( p->second );
    00203         return found;
    00204 }
    00205
    00206
    00207 template<class T>
    00208 bool ConfigFile::readInto( T& var, const string& key, const T& value ) const
    00209 {
    00210         // Get the value corresponding to key and store in var
    00211         // Return true if key is found
    00212         // Otherwise set var to given default
    00213         mapci p = myContents.find(key);
    00214         bool found = ( p != myContents.end() );
    00215         if( found )
    00216                 var = string_as_T<T>( p->second );
    00217         else
    00218                 var = value;
    00219         return found;
    00220 }
    00221
    00222
    00223 template<class T>
    00224 void ConfigFile::add( string key, const T& value )
    00225 {
    00226         // Add a key with given value
    00227         string v = T_as_string( value );
    00228         trim(key);
    00229         trim(v);
    00230         myContents[key] = v;
    00231         return;
    00232 }
    00233
    00234 #endif  // CONFIGFILE_H
    00235
    00236 // Release notes:
    00237 // v1.0  21 May 1999
    00238 //   + First release
    00239 //   + Template read() access only through non-member readConfigFile()
    00240 //   + ConfigurationFileBool is only built-in helper class
    00241 //
    00242 // v2.0  3 May 2002
    00243 //   + Shortened name from ConfigurationFile to ConfigFile
    00244 //   + Implemented template member functions
    00245 //   + Changed default comment separator from % to #
    00246 //   + Enabled reading of multiple-line values
    00247 //
    00248 // v2.1  24 May 2004
    00249 //   + Made template specializations inline to avoid compiler-dependent linkage
    00250 //   + Allowed comments within multiple-line values
    00251 //   + Enabled blank line termination for multiple-line values
    00252 //   + Added optional sentry to detect end of configuration file
    00253 //   + Rewrote messy trimWhitespace() function as elegant trim()