Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/trunk/src/lib/parser/ini_parser/ini_parser.cc @ 5951

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

orxonox/trunk: cool functions

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