1 // ConfigFile.h
2 // Class for reading named values from configuration files
3 // Richard J. Wagner v2.1 24 May 2004 wagnerr@umich.edu
4 // Modified by Joey Parrish, June 2011 joey.parrish@gmail.com
5
6 // Copyright (c) 2004 Richard J. Wagner
7 //
8 // Permission is hereby granted, free of charge, to any person obtaining a copy
9 // of this software and associated documentation files (the "Software"), to
10 // deal in the Software without restriction, including without limitation the
11 // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
12 // sell copies of the Software, and to permit persons to whom the Software is
13 // furnished to do so, subject to the following conditions:
14 //
15 // The above copyright notice and this permission notice shall be included in
16 // all copies or substantial portions of the Software.
17 //
18 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
23 // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
24 // IN THE SOFTWARE.
25
26 // Typical usage
27 // -------------
28 //
29 // Given a configuration file "settings.inp":
30 // atoms = 25
31 // length = 8.0 # nanometers
32 // name = Reece Surcher
33 //
34 // Named values are read in various ways, with or without default values:
35 // ConfigFile config( "settings.inp" );
36 // int atoms = config.read<int>( "atoms" );
37 // double length = config.read( "length", 10.0 );
38 // string author, title;
39 // config.readInto( author, "name" );
40 // config.readInto( title, "title", string("Untitled") );
41 //
42 // See file example.cpp for more examples.
43
44 #ifndef CONFIGFILE_H
45 #define CONFIGFILE_H
46
47 #include <string>
48 #include <map>
49 #include <vector>
50 #include <iostream>
51 #include <fstream>
52 #include <sstream>
53
54 using std::string;
55
56 class ConfigFile {
57 // Data
58 protected:
59 string myDelimiter; // separator between key and value
60 string myComment; // separator between value and comments
61 string mySentry; // optional string to signal end of file
62 std::map<string,string> myContents; // extracted keys and values
63 std::vector<string> myLines;
64 std::map<string,int> myLineNumbers;
65
66 typedef std::map<string,string>::iterator mapi;
67 typedef std::map<string,string>::const_iterator mapci;
68
69 // Methods
70 public:
71 ConfigFile( string filename,
72 string delimiter = "=",
73 string comment = "#",
74 string sentry = "" );
75 ConfigFile();
76
77 // Search for key and read value or optional default value
78 template<class T> T read( const string& key ) const; // call as read<T>
79 template<class T> T read( const string& key, const T& value ) const;
80 template<class T> bool readInto( T& var, const string& key ) const;
81 template<class T>
82 bool readInto( T& var, const string& key, const T& value ) const;
83
84 // Modify keys and values
85 template<class T> void add( string key, const T& value );
86 void remove( const string& key );
87
88 // Check whether key exists in configuration
89 bool keyExists( const string& key ) const;
90
91 // Check or change configuration syntax
getDelimiter()92 string getDelimiter() const { return myDelimiter; }
getComment()93 string getComment() const { return myComment; }
getSentry()94 string getSentry() const { return mySentry; }
setDelimiter(const string & s)95 string setDelimiter( const string& s )
96 { string old = myDelimiter; myDelimiter = s; return old; }
setComment(const string & s)97 string setComment( const string& s )
98 { string old = myComment; myComment = s; return old; }
99
100 // Write or read configuration
101 friend std::ostream& operator<<( std::ostream& os, const ConfigFile& cf );
102 friend std::istream& operator>>( std::istream& is, ConfigFile& cf );
103
104 protected:
105 template<class T> static string T_as_string( const T& t );
106 template<class T> static T string_as_T( const string& s );
107 static void trim( string& s );
108
109
110 // Exception types
111 public:
112 struct file_not_found {
113 string filename;
114 file_not_found( const string& filename_ = string() )
filenamefile_not_found115 : filename(filename_) {} };
116 struct key_not_found { // thrown only by T read(key) variant of read()
117 string key;
118 key_not_found( const string& key_ = string() )
keykey_not_found119 : key(key_) {} };
120 };
121
122
123 /* static */
124 template<class T>
T_as_string(const T & t)125 string ConfigFile::T_as_string( const T& t )
126 {
127 // Convert from a T to a string
128 // Type T must support << operator
129 std::ostringstream ost;
130 ost << t;
131 return ost.str();
132 }
133
134
135 /* static */
136 template<>
137 inline string ConfigFile::T_as_string<bool>( const bool& t )
138 {
139 return t ? "true" : "false";
140 }
141
142
143 /* static */
144 template<class T>
string_as_T(const string & s)145 T ConfigFile::string_as_T( const string& s )
146 {
147 // Convert from a string to a T
148 // Type T must support >> operator
149 T t;
150 std::istringstream ist(s);
151 ist >> t;
152 return t;
153 }
154
155
156 /* static */
157 template<>
158 inline string ConfigFile::string_as_T<string>( const string& s )
159 {
160 // Convert from a string to a string
161 // In other words, do nothing
162 return s;
163 }
164
165
166 /* static */
167 template<>
168 inline bool ConfigFile::string_as_T<bool>( const string& s )
169 {
170 // Convert from a string to a bool
171 // Interpret "false", "F", "no", "n", "0" as false
172 // Interpret "true", "T", "yes", "y", "1", "-1", or anything else as true
173 bool b = true;
174 string sup = s;
175 for( string::iterator p = sup.begin(); p != sup.end(); ++p )
176 *p = toupper(*p); // make string all caps
177 if( sup==string("FALSE") || sup==string("F") ||
178 sup==string("NO") || sup==string("N") ||
179 sup==string("0") || sup==string("NONE") )
180 b = false;
181 return b;
182 }
183
184
185 template<class T>
read(const string & key)186 T ConfigFile::read( const string& key ) const
187 {
188 // Read the value corresponding to key
189 mapci p = myContents.find(key);
190 if( p == myContents.end() ) throw key_not_found(key);
191 return string_as_T<T>( p->second );
192 }
193
194
195 template<class T>
read(const string & key,const T & value)196 T ConfigFile::read( const string& key, const T& value ) const
197 {
198 // Return the value corresponding to key or given default value
199 // if key is not found
200 mapci p = myContents.find(key);
201 if( p == myContents.end() ) return value;
202 return string_as_T<T>( p->second );
203 }
204
205
206 template<class T>
readInto(T & var,const string & key)207 bool ConfigFile::readInto( T& var, const string& key ) const
208 {
209 // Get the value corresponding to key and store in var
210 // Return true if key is found
211 // Otherwise leave var untouched
212 mapci p = myContents.find(key);
213 bool found = ( p != myContents.end() );
214 if( found ) var = string_as_T<T>( p->second );
215 return found;
216 }
217
218
219 template<class T>
readInto(T & var,const string & key,const T & value)220 bool ConfigFile::readInto( T& var, const string& key, const T& value ) const
221 {
222 // Get the value corresponding to key and store in var
223 // Return true if key is found
224 // Otherwise set var to given default
225 mapci p = myContents.find(key);
226 bool found = ( p != myContents.end() );
227 if( found )
228 var = string_as_T<T>( p->second );
229 else
230 var = value;
231 return found;
232 }
233
234
235 template<class T>
add(string key,const T & value)236 void ConfigFile::add( string key, const T& value )
237 {
238 // Add a key with given value
239 string v = T_as_string( value );
240 trim(key);
241 trim(v);
242 mapci p = myContents.find(key);
243 if (p == myContents.end()) {
244 myLineNumbers[key] = myLines.size();
245 // we need to be sure that we have a line availiable to add key
246 myLines.push_back("");
247 }
248 myLines[myLineNumbers[key]] = key + " " + myDelimiter + " " + v;
249 myContents[key] = v;
250 return;
251 }
252
253 #endif // CONFIGFILE_H
254
255 // Release notes:
256 // v1.0 21 May 1999
257 // + First release
258 // + Template read() access only through non-member readConfigFile()
259 // + ConfigurationFileBool is only built-in helper class
260 //
261 // v2.0 3 May 2002
262 // + Shortened name from ConfigurationFile to ConfigFile
263 // + Implemented template member functions
264 // + Changed default comment separator from % to #
265 // + Enabled reading of multiple-line values
266 //
267 // v2.1 24 May 2004
268 // + Made template specializations inline to avoid compiler-dependent linkage
269 // + Allowed comments within multiple-line values
270 // + Enabled blank line termination for multiple-line values
271 // + Added optional sentry to detect end of configuration file
272 // + Rewrote messy trimWhitespace() function as elegant trim()
273