Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/branches/spaceshipcontrol/src/lib/parser/ini_parser/ini_parser.cc @ 6762

Last change on this file since 6762 was 5953, checked in by bensch, 19 years ago

orxonox/trunk: ini_parser safer now

File size: 21.0 KB
Line 
1/*
2   orxonox - the future of 3D-vertical-scrollers
3
4   Copyright (C) 2004 orx
5
6   This program is free software; you can redistribute it and/or modify
7   it under the terms of the GNU General Public License as published by
8   the Free Software Foundation; either version 2, or (at your option)
9   any later version.
10
11   ### File Specific:
12   main-programmer: Benjamin Grauer
13   co-programmer: Christian Meyer
14
15   2005-08-14: complete reimplementation:
16               now the File is parsed at the initialisation,
17               and informations is gathered there.
18*/
19
20
21#include "ini_parser.h"
22
23#include <stdlib.h>
24#include <string.h>
25
26#if HAVE_CONFIG_H
27#include <config.h>
28#endif
29
30#ifdef DEBUG
31 #include "../../../defs/debug.h"
32#else
33 #define PRINTF(x) printf
34#endif
35
36using namespace std;
37
38/**
39 * @brief constructs an IniParser using a file
40 * @param fileName: the path and name of the file to parse
41 */
42IniParser::IniParser (const char* fileName)
43{
44  this->fileName = NULL;
45  this->comment = NULL;
46
47  if (fileName != NULL)
48    this->readFile(fileName);
49}
50
51
52/**
53 * @brief removes the IniParser from memory
54 */
55IniParser::~IniParser ()
56{
57  this->deleteSections();
58  this->setFileName(NULL);
59}
60
61
62/**
63 * @brief removes all the sections. This is like delete, but even cooler :)
64 */
65void IniParser::deleteSections()
66{
67  // in all sections
68  while(!this->sections.empty())
69  {
70     IniSection section = this->sections.front();
71
72    // in all entries of the sections
73    while(!section.entries.empty())
74    {
75      // delete all strings of entries.
76      IniEntry entry = section.entries.front();
77      delete[] entry.name;
78      delete[] entry.value;
79      delete[] entry.comment;
80      section.entries.pop_front();
81    }
82    // delete all Sections
83    delete[] section.name;
84    delete[] section.comment;
85    this->sections.pop_front();
86  }
87  this->currentSection = this->sections.end();
88  this->setFileName(NULL);
89}
90
91
92/**
93 * @brief sets the Name of the input-file
94 * @param fileName The new FileName to set to the IniParser
95 * If fileName is NULL the new Name will be set to NULL too.
96 */
97void IniParser::setFileName(const char* fileName)
98{
99  if (this->fileName != NULL)
100    delete[] this->fileName;
101  if  (this->comment != NULL)
102    delete[] this->comment;
103  this->comment = NULL;
104
105  if (fileName != NULL)
106  {
107    this->fileName = new char[strlen(fileName)+1];
108    strcpy(this->fileName, fileName);
109  }
110  else
111    this->fileName = NULL;
112}
113
114
115/**
116 * @brief opens a file to parse
117 * @param fileName: path and name of the new file to parse
118 * @return true on success false otherwise;
119 *
120 * If there was already an opened file, the file will be closed,
121 * and the new one will be opened.
122 */
123bool IniParser::readFile(const char* fileName)
124{
125  FILE*    stream;           //< The stream we use to read the file.
126  int      lineCount = 0;    //< The Count of lines.
127
128  if (this->fileName != NULL)
129    this->deleteSections();
130  if( fileName == NULL)
131    return false;
132
133  if( (stream = fopen (fileName, "r")) == NULL)
134  {
135    PRINTF(1)("IniParser could not open %s\n", fileName);
136    return false;
137  }
138  else
139  {
140    this->setFileName(fileName);
141
142    /////////////////////////////
143    // READING IN THE INI-FILE //
144    /////////////////////////////
145    char lineBuffer[PARSELINELENGHT];
146    char buffer[PARSELINELENGHT];
147    const char* lineBegin;
148    char* ptr;
149
150    while( fgets (lineBuffer, PARSELINELENGHT, stream))
151    {
152      lineBegin = lineBuffer;
153      // remove newline char, and \0-terminate
154      if( (ptr = strchr( lineBuffer, '\n')) != NULL)
155        *ptr = 0;
156      // cut up to the beginning of the line.
157      while((*lineBegin == ' ' || *lineBegin == '\t') && lineBegin < lineBuffer + strlen(lineBuffer))
158        ++lineBegin;
159
160      // check if we have a FileComment
161      if ( (*lineBegin == '#' || *lineBegin == ';'))
162      {
163        char* newCommenLine = new char[strlen(lineBegin)+1];
164        strcpy(newCommenLine, lineBegin);
165        this->commentList.push_back(newCommenLine);
166        continue;
167      }
168      if (lineCount == 0 && !this->commentList.empty())
169      {
170        this->setFileComment();
171        lineCount++;
172      }
173
174      // check for section identifyer
175      else if( sscanf (lineBegin, "[%s", buffer) == 1)
176      {
177        if( (ptr = strchr( buffer, ']')) != NULL)
178        {
179          *ptr = 0;
180          this->addSection(buffer);
181          this->setSectionComment();
182        }
183      }
184      // check for Entry identifier (Entry = Value)
185      else if( (ptr = strchr( lineBegin, '=')) != NULL)
186      {
187        if (currentSection == NULL)
188        {
189          PRINTF(2)("Not in a Section yet for %s\n", lineBegin);
190          lineCount++;
191          continue;
192        }
193        if( ptr == lineBegin) {
194          lineCount++;
195          continue;
196        }
197        char* valueBegin = ptr+1;
198        while ((*valueBegin == ' ' || *valueBegin == '\t') && valueBegin <= lineBegin + strlen(lineBegin))
199          ++valueBegin;
200        char* valueEnd = valueBegin + strlen(valueBegin)-1;
201        while ((*valueEnd == ' ' || *valueEnd == '\t') && valueEnd >= valueBegin)
202          --valueEnd;
203        valueEnd[1] = '\0';
204        char* nameEnd = ptr-1;
205        while ((*nameEnd == ' ' || *nameEnd == '\t' ) && nameEnd >= lineBegin)
206          --nameEnd;
207        nameEnd[1] = '\0';
208
209        this->addVar(lineBegin, valueBegin);
210        this->setEntryComment();
211
212        lineCount++;
213      }
214    }
215  }
216  this->currentSection = this->sections.begin();
217  if (!this->sections.empty())
218    this->currentEntry = (*this->currentSection).entries.begin();
219
220  fclose(stream);
221  return true;
222}
223
224
225/**
226 * @brief opens a file and writes to it
227 * @param fileName: path and name of the new file to write to
228 * @return true on success false otherwise
229 */
230bool IniParser::writeFile(const char* fileName) const
231{
232  FILE*    stream;           //!< The stream we use to read the file.
233  if( fileName == NULL && (fileName = this->fileName) == NULL )
234    return false;
235
236  if( (stream = fopen (fileName, "w")) == NULL)
237  {
238    PRINTF(1)("IniParser could not open %s\n", fileName);
239    return false;
240  }
241  else
242  {
243    if (this->comment != NULL)
244      fprintf(stream, "%s\n\n", this->comment);
245
246    std::list<IniSection>::const_iterator section;
247    for (section = this->sections.begin(); section != this->sections.end(); section++)
248      {
249        if ((*section).comment != NULL)
250          fprintf(stream, "%s", (*section).comment);
251        fprintf(stream, "\n [%s]\n", (*section).name);
252
253        std::list<IniEntry>::const_iterator entry;
254        for (entry = (*section).entries.begin(); entry != (*section).entries.end(); entry++)
255        {
256          if ((*entry).comment != NULL)
257            fprintf(stream, "%s", (*entry).comment);
258          fprintf(stream, "   %s = %s\n", (*entry).name, (*entry).value);
259         }
260      }
261  }
262  fclose(stream);
263}
264
265void IniParser::setFileComment(const char* fileComment)
266{
267  if (this->comment != NULL)
268    delete this->comment;
269
270  if (fileComment != NULL)
271  {
272    this->comment = new char[strlen(fileComment)+1];
273    strcpy(this->comment, fileComment);
274  }
275  else
276    this->comment = NULL;
277}
278
279
280/**
281 * @brief adds a section to the list of Sections,
282 * if no Section list is availiable, it will create it
283 * @param sectionName the Name of the section to add
284 * @return true on success... there is only success or segfault :)
285 */
286bool IniParser::addSection(const char* sectionName)
287{
288  if (sectionName == NULL)
289    return false;
290  this->sections.push_back(IniSection());
291  this->sections.back().comment = NULL;
292  this->sections.back().name = new char[strlen(sectionName)+1];
293  strcpy(this->sections.back().name, sectionName);
294
295  this->currentSection = --this->sections.end();
296  if (!this->sections.empty())
297      this->currentEntry = (*this->currentSection).entries.begin();
298  PRINTF(5)("Added Section %s\n", sectionName);
299  return true;
300}
301
302
303/**
304 * @brief Set the parsing cursor to the specified section
305 * @param sectionName: the name of the section to set the cursor to
306 * @return true on success or false if the section could not be found
307 */
308bool IniParser::getSection(const char* sectionName)
309{
310  this->currentSection = this->getSectionIT(sectionName);
311  if (this->currentSection != this->sections.end())
312  {
313    this->currentEntry = (*this->currentSection).entries.begin();
314    return true;
315  }
316  else
317    return false;
318}
319
320/**
321 *
322 */
323void IniParser::setSectionComment(const char* comment, const char* sectionName)
324{
325  std::list<IniSection>::iterator section = this->getSectionIT(sectionName);
326  if (section == this->sections.end())
327    return;
328
329  if ((*section).comment != NULL)
330    delete[] (*section).comment;
331  if (comment != NULL)
332  {
333    (*section).comment = new char[strlen (comment)+1];
334    strcpy((*section).comment, comment);
335  }
336  else
337    (*section).comment = NULL;
338}
339
340/**
341 * @param sectionName the Section to query for
342 * @returns the Comment, or NULL on error.
343 */
344const char* IniParser::getSectionComment(const char* sectionName) const
345{
346  std::list<IniSection>::const_iterator section = this->getSectionIT(sectionName);
347  if (section != this->sections.end())
348    return (*section).comment;
349  else
350    return NULL;
351}
352
353
354/**
355 * @brief moves to the first section
356 */
357void IniParser::firstSection()
358{
359  this->currentSection = this->sections.begin();
360  if (!this->sections.empty())
361    this->currentEntry = (*this->currentSection).entries.begin();
362}
363
364
365/**
366 * @brief searches the next section
367 * @returns the name of the section if found, NULL otherwise
368 */
369const char* IniParser::nextSection()
370{
371  if (this->currentSection == this->sections.end())
372    return NULL;
373
374  this->currentSection++;
375
376  if (this->currentSection != this->sections.end())
377    {
378      this->currentEntry = (*this->currentSection).entries.begin();
379      return this->currentSection->name;
380    }
381  else
382    return NULL;
383}
384
385
386/**
387 * @brief adds a new Entry to either the currentSection or the section called by sectionName
388 * @param entryName the Name of the Entry to add
389 * @param value the value to assign to this entry
390 * @param sectionName if NULL then this entry will be set to the currentSection
391 * otherwise to the section refered to by sectionName.
392 * If both are NULL no entry will be added
393 * @return true if everything is ok false on error
394 */
395bool IniParser::addVar(const char* entryName, const char* value, const char* sectionName)
396{
397  std::list<IniSection>::iterator section;
398
399  if (sectionName != NULL)
400  {
401    for (section = this->sections.begin(); section != this->sections.end(); section++)
402      if (!strcmp((*section).name, sectionName))
403        break;
404  }
405  else
406    section = this->currentSection;
407
408  if (section == this->sections.end())
409    return false;
410
411  if (section == this->sections.end())
412  {
413    PRINTF(2)("section '%s' not found for value '%s'\n", sectionName, entryName);
414    return false;
415  }
416  else
417  {
418    (*section).entries.push_back(IniEntry());
419    (*section).entries.back().comment = NULL;
420    (*section).entries.back().name = new char[strlen(entryName)+1];
421    strcpy((*section).entries.back().name, entryName);
422    (*section).entries.back().value = new char[strlen(value)+1];
423    strcpy((*section).entries.back().value, value);
424    PRINTF(5)("Added Entry %s with Value '%s' to Section %s\n",
425              (*section).entries.back().name,
426              (*section).entries.back().value,
427              (*section).name);
428    this->currentEntry = --(*section).entries.end();
429    return true;
430  }
431}
432
433
434/**
435 * @brief directly acesses an entry in a section
436 * @param entryName: the name of the entry to find
437 * @param sectionName: the section where the entry is to be found
438 * @param defaultValue: what should be returned in case the entry cannot be found
439 * @return a pointer to a buffer conatining the value of the specified entry. This buffer will contain the data specified in defvalue in case the entry wasn't found
440 *
441 *  The returned pointer points to an internal buffer, so do not free it on your own. Do not give a NULL pointer to defvalue, this will certainly
442 * lead to unwanted behaviour.
443*/
444const char* IniParser::getVar(const char* entryName, const char* sectionName, const char* defaultValue) const
445{
446  if (this->fileName != NULL)
447  {
448    std::list<IniEntry>::const_iterator entry = this->getEntryIT(entryName, sectionName);
449    if (entry != NULL &&  !strcmp((*entry).name, entryName))
450      return (*entry).value;
451    PRINTF(2)("Entry '%s' in section '%s' not found.\n", entryName, sectionName);
452
453  }
454  else
455    PRINTF(2)("no File opened\n");
456
457  return defaultValue;
458
459}
460
461/**
462 * Set the Comment of a specified Entry.
463 * @param comment the Comment to set
464 * @param entryName the Name of the Entry
465 * @param sectionName the Name of the Section
466 */
467void IniParser::setEntryComment(const char* comment, const char* entryName, const char* sectionName)
468{
469  std::list<IniEntry>::iterator entry = this->getEntryIT(entryName, sectionName);
470
471  if ((*entry).comment != NULL)
472    delete[] (*entry).comment;
473  if (comment != NULL)
474  {
475    (*entry).comment = new char[strlen (comment)+1];
476    strcpy((*entry).comment, comment);
477  }
478  else
479    (*entry).comment = NULL;
480
481
482}
483
484/**
485 * @param entryName the Entry to query for
486 * @param sectionName the Section to Query for
487 * @returns the queried Comment.
488 */
489const char* IniParser::getEntryComment(const char* entryName, const char* sectionName) const
490{
491  std::list<IniEntry>::const_iterator entry = this->getEntryIT(entryName, sectionName);
492
493  return (*entry).comment;
494}
495
496
497/**
498 * @brief moves to the first Variable of the current Section
499 */
500void IniParser::firstVar()
501{
502  if (!this->sections.empty() &&
503       this->currentSection != this->sections.end())
504    this->currentEntry = (*this->currentSection).entries.begin();
505}
506
507
508/**
509 * @brief gets the next VarName = VarValue pair from the parsing stream
510 * @return true on success, false otherwise (in the latter case name and value will be NULL)
511 */
512bool IniParser::nextVar()
513{
514  if ( this->sections.empty()
515       || this->currentSection == this->sections.end()
516       || this->currentEntry == (*this->currentSection).entries.end())
517    return false;
518
519  this->currentEntry++;
520
521  if (this->currentEntry == (*this->currentSection).entries.end())
522    return false;
523  else
524    return true;
525}
526
527
528
529/**
530 * @returns the name of the Current selected Section
531 */
532const char* IniParser::getCurrentSection() const
533{
534  if (!this->sections.empty() &&
535      this->currentSection != this->sections.end())
536    return this->currentSection->name;
537  else
538    return NULL;
539 }
540
541
542/**
543 * @returns the current entries Name, or NULL if we havn't selected a Entry
544 */
545const char* IniParser::getCurrentName() const
546{
547 if (!this->sections.empty() &&
548     this->currentSection != this->sections.end() &&
549     this->currentEntry != (*this->currentSection).entries.end())
550   return (*this->currentEntry).name;
551 else
552   return NULL;
553}
554
555/**
556 * @returns the current entries Value, or NULL if we havn't selected a Entry
557 */
558const char* IniParser::getCurrentValue() const
559{
560  if (!this->sections.empty() &&
561      this->currentSection != this->sections.end() &&
562      this->currentEntry != (*this->currentSection).entries.end())
563    return (*this->currentEntry).value;
564  else
565    return NULL;
566}
567
568
569/**
570 * Finds the Section Iterator of the Section Called sectionName
571 * @param sectionName the Name of the Section to get the Iterator from
572 */
573std::list<IniParser::IniSection>::const_iterator IniParser::getSectionIT(const char* sectionName) const
574{
575  std::list<IniSection>::const_iterator section = this->currentSection;
576  if (sectionName == NULL)
577    return this->currentSection;
578  else
579    for (section = this->sections.begin(); section != this->sections.end(); section++)
580      if (!strcmp((*section).name, sectionName))
581        break;
582  return section;
583}
584
585
586/**
587 * Finds the Section Iterator of the Section Called sectionName
588 * @param sectionName the Name of the Section to get the Iterator from
589 */
590std::list<IniParser::IniSection>::iterator IniParser::getSectionIT(const char* sectionName)
591{
592  std::list<IniSection>::iterator section = this->currentSection;
593  if (sectionName == NULL)
594    return this->currentSection;
595  else
596    for (section = this->sections.begin(); section != this->sections.end(); section++)
597      if (!strcmp((*section).name, sectionName))
598        break;
599  return section;
600}
601
602
603/**
604 * Finds the Entry Iterator of the Section Called sectionName and entry called EntryName
605 * @param entryName the Name of the Entry to get the Iterator from
606 * @param sectionName the Name of the Section to get the Iterator from
607 */
608std::list<IniParser::IniEntry>::const_iterator IniParser::getEntryIT(const char* entryName, const char* sectionName) const
609{
610  if (entryName == NULL)
611    return this->currentEntry;
612  std::list<IniSection>::const_iterator section = this->getSectionIT(sectionName);
613  std::list<IniEntry>::const_iterator entry = this->currentEntry;
614
615  if (section != this->sections.end())
616    for (entry = (*section).entries.begin(); entry != (*section).entries.end(); entry++)
617      if (!strcmp((*entry).name, entryName))
618        break;
619  if (entry == (*section).entries.end())
620    return NULL;
621  else
622    return entry;
623}
624
625
626/**
627 * Finds the Entry Iterator of the Section Called sectionName and entry called EntryName
628 * @param entryName the Name of the Entry to get the Iterator from
629 * @param sectionName the Name of the Section to get the Iterator from
630 */
631std::list<IniParser::IniEntry>::iterator IniParser::getEntryIT(const char* entryName, const char* sectionName)
632{
633  if (entryName == NULL)
634    return this->currentEntry;
635  std::list<IniSection>::iterator section = this->getSectionIT(sectionName);
636  std::list<IniEntry>::iterator entry = this->currentEntry;
637
638  if (section != this->sections.end())
639    for (entry = (*section).entries.begin(); entry != (*section).entries.end(); entry++)
640      if (!strcmp((*entry).name, entryName))
641        break;
642  if (entry == (*section).entries.end())
643    return NULL;
644  else
645    return entry;
646}
647
648
649/**
650 * takes lines together to form one FileComment, ereasing the commentList
651 */
652void IniParser::setFileComment()
653{
654  if (this->comment != NULL)
655    delete[] this->comment;
656
657  if (this->commentList.empty()) {
658    this->comment = NULL;
659    return;
660  }
661
662  unsigned int stringLength = 1;
663  std::list<char*>::iterator comment;
664  for (comment = this->commentList.begin(); comment != this->commentList.end(); comment++)
665    stringLength += strlen((*comment)) +1;
666
667  this->comment = new char[stringLength];
668  this->comment[0] = '\0';
669  while (!this->commentList.empty())
670  {
671    if (*this->comment != '\0')
672      strcat(this->comment, "\n");
673    strcat(this->comment, this->commentList.front());
674    delete[] this->commentList.front();
675    this->commentList.pop_front();
676  }
677}
678
679/**
680 * takes lines together to form one SectionComment, ereasing the commentList
681 */
682void IniParser::setSectionComment()
683{
684  if ((*this->currentSection).comment != NULL)
685    delete[] (*this->currentSection).comment;
686
687  if (this->commentList.empty()) {
688    (*this->currentSection).comment = NULL;
689    return;
690  }
691
692  unsigned int stringLength = 1;
693  std::list<char*>::iterator comment;
694  for (comment = this->commentList.begin(); comment != this->commentList.end(); comment++)
695    stringLength += strlen((*comment)) +1;
696
697  (*this->currentSection).comment = new char[stringLength];
698  (*this->currentSection).comment[0] = '\0';
699  while (!this->commentList.empty())
700  {
701    if (*(*this->currentSection).comment != '\0')
702      strcat((*this->currentSection).comment, "\n");
703    strcat((*this->currentSection).comment, this->commentList.front());
704    delete[] this->commentList.front();
705    this->commentList.pop_front();
706  }
707}
708
709/**
710 * takes lines together to form one EntryComment, ereasing the commentList
711 */
712void IniParser::setEntryComment()
713{
714  if ((*this->currentEntry).comment != NULL)
715    delete[] (*this->currentEntry).comment;
716
717  if (this->commentList.empty()) {
718    (*this->currentEntry).comment = NULL;
719    return;
720  }
721
722  unsigned int stringLength = 1;
723  std::list<char*>::iterator comment;
724  for (comment = this->commentList.begin(); comment != this->commentList.end(); comment++)
725    stringLength += strlen((*comment)) +1;
726
727  (*this->currentEntry).comment = new char[stringLength];
728  (*this->currentEntry).comment[0] = '\0';
729  while (!this->commentList.empty())
730  {
731    if (*(*this->currentEntry).comment != '\0')
732      strcat((*this->currentEntry).comment, "\n");
733    strcat((*this->currentEntry).comment, this->commentList.front());
734    delete[] this->commentList.front();
735    this->commentList.pop_front();
736  }
737
738}
739
740
741/**
742 * @brief output the whole tree in a nice and easy way.
743 */
744void IniParser::debug() const
745{
746  PRINTF(0)("Iniparser %s - debug\n", this->fileName);
747  if (this->comment != NULL)
748    PRINTF(0)("FileComment:\n %s\n\n", this->comment);
749
750  if (this->fileName != NULL)
751  {
752    std::list<IniSection>::const_iterator section;
753    for (section = this->sections.begin(); section != this->sections.end(); section++)
754    {
755      if ((*section).comment != NULL)
756        PRINTF(0)(" %s\n", (*section).comment);
757      PRINTF(0)(" [%s]\n", (*section).name);
758
759      std::list<IniEntry>::const_iterator entry;
760      for (entry = (*section).entries.begin(); entry != (*section).entries.end(); entry++)
761      {
762        if ((*entry).comment != NULL)
763          PRINTF(0)(" %s\n", (*entry).comment);
764        PRINTF(0)("   '%s' -> '%s'\n", (*entry).name, (*entry).value);
765      }
766    }
767  }
768  else
769    PRINTF(1)("no opened ini-file.\n");
770}
771
Note: See TracBrowser for help on using the repository browser.