Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/branches/std/src/lib/parser/ini_parser/ini_parser.cc @ 7210

Last change on this file since 7210 was 7206, checked in by rennerc, 20 years ago

fixed some bugs

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