Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/branches/gui/src/lib/parser/ini_parser/ini_parser.cc @ 8529

Last change on this file since 8529 was 7729, checked in by bensch, 18 years ago

orxonox/trunk: better debug names
As DEBUG and ERROR are already given to windows.h and other files:
DEBUG is renamed to DEBUG_LEVEL
and all
NO, ERR, WARN, INFO, DEBUG, vDEBUG
are renamed to
ORX_NONE, ORX_ERR, ORX_WARN, ORX_INFO, ORX_DEBUG, ORX_vDEBUG

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