/* orxonox - the future of 3D-vertical-scrollers Copyright (C) 2004 orx This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. ### File Specific: main-programmer: Christian Meyer co-programmer: ... */ #include "ini_parser.h" using namespace std; IniParser::IniParser (char* filename) { stream = NULL; bInSection = false; open_file (filename); } IniParser::~IniParser () { if( stream != NULL) fclose (stream); } int IniParser::open_file( char* filename) { if( filename == NULL) return -1; if( stream != NULL) fclose (stream); if( (stream = fopen (filename, "r")) == NULL) { printf("IniParser could not open %s\n", filename); return -1; } bInSection = false; return 0; } int IniParser::get_section( char* section) { bInSection = false; if( stream == NULL) return -1; char linebuffer[PARSELINELENGHT]; char secbuffer[PARSELINELENGHT]; char* ptr; rewind (stream); while( !feof( stream)) { // get next line fgets (linebuffer, PARSELINELENGHT, stream); // remove newline char if( (ptr = strchr( linebuffer, '\n')) != NULL) *ptr = 0; // check for section identifyer if( sscanf (linebuffer, "[%s", secbuffer) == 1) { if( (ptr = strchr( secbuffer, ']')) != NULL) { *ptr = 0; if( !strcmp( secbuffer, section)) { bInSection = true; return 0; } } } } return -1; } int IniParser::next_var( char* name, char* value) { if( stream == NULL) { bInSection = false; return -1; } if( !bInSection) return -1; char linebuffer[PARSELINELENGHT]; char* ptr; while( !feof( stream)) { // get next line fgets (linebuffer, PARSELINELENGHT, stream); // remove newline char if( (ptr = strchr( linebuffer, '\n')) != NULL) *ptr = 0; if( linebuffer[0] == '[') { bInSection = false; return -1; } if( (ptr = strchr( linebuffer, '=')) != NULL) { if( ptr == linebuffer) continue; strcpy (value, &ptr[1]); strncpy (name, linebuffer, strlen (linebuffer) - strlen (value) - 1); return 0; } } return -1; } char* IniParser::get_var( char* name, char* section, char* defvalue = "") { strcpy (internbuf, defvalue); if( get_section (section) == -1) return internbuf; char namebuf[PARSELINELENGHT]; char valuebuf[PARSELINELENGHT]; while( next_var (namebuf, valuebuf) != -1) { if( !strcmp (name, namebuf)) { strcpy (internbuf, valuebuf); return internbuf; } } return internbuf; }