| // name/value pairs, one per line. Lines beginning with
|
| // a '#' pound characters are comments. The format of
|
| // the name/value pairs is 'name' 'space' 'value'.
|
| // The 'value' portion begins following the first space
|
| // one the line, and ends at a carriage return.
|
| //
|
| // Parameters:
|
| // list Reference to list that will be
|
| // populated with name/value pairs loaded
|
| // from the file.
|
| // config_file Name of the configuration file to load.
|
| //
|
| // Returns:
|
| // The number of name/value pairs loaded as an integer.
|
| //
|
| int LoadConfig( CNVList& list, const String& config_file )
|
| {
|
| FILE * f ;
|
| char buffer[300] ; // increase as necessary
|
| String s ;
|
| String name ;
|
| String value ;
|
| int count = 0 ;
|
|
|
| f = fopen( (char *) String(config_file), "rt" ) ;
|
| if ( f )
|
| {
|
| // Loop while there are lines to read.
|
| // If you have unusually long lines, you could
|
| // read directly into a String object, which
|
| // can grow dynamically.
|
| while ( fgets( buffer, sizeof(buffer), f ) != NULL )
|
| {
|
| s = buffer ;
|
| s.LTrim() ;
|
| s.RTrim() ;
|
| s.RTrim( '\n' ) ;
|
|
|
| // If line is not a comment line
|
| if ( s[0] != '#' )
|
| {
|
| // If you want the config file to
|
| // use a separator other than a space
|
| // between the name and value (e.g., a
|
| // an '=' characters as in "name=value",
|
| // add it as a parameter to GetNextToken().
|
| //
|
| name = s.GetNextToken() ;
|
| value = s ; // the remainder of the string
|
|
|
| // Add the pair to the list
|
| list.Value( name, value ) ;
|
|
|
| // Keep track of the number of pairs read
|
| ++count ;
|
| }
|
| }
|
| fclose( f ) ;
|
| }
|
|
|
| return count ;
|
| }
|
|
|
|
|
| //
|
| // Demonstrate use of the LoadConfig() routine to
|
| // load the contents of a configuration file
|
| // as a name/value pair list.
|
| //
|
| int main( int argc, char ** argv )
|
| {
|
| CNVList config ;
|
| String name ;
|
| String value ;
|
|
|
| // Load the config file into memory
|
| LoadConfig( config, "list.cfg" ) ;
|
|
|
| // Dump contents of the config file to console
|
| Boolean good_data = config.Enumerate(name, value, TRUE);
|
| while ( good_data )
|
| {
|
| // You can also get/set values using
|
| // the CNVList::Value() method.
|
|
|
| cout << name << ": " << value << "\n" ;
|
| good_data = config.Enumerate( name, value ) ;
|
| }
|
|
|
| return 0 ;
|
| }
|
| |