Mail Archives: djgpp/1999/11/07/22:38:52
*IniUtils.h*
#ifndef __INI_FILE__
#define __INI_FILE__
class IniFile {
private:
char* file;
char* activeSecName;
char** activeSec;
public:
IniFile();
IniFile(char* file);
~IniFile();
void setFile(char* file);
void setActiveSection(char* secName);
char* getValue(char* keyword);
char* getActiveSectionName();
};
#endif __INI_FILE__
*IniUtils.cpp*
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fstream.h>
#include <iostream.h>
#include "StringUtils.h"
IniFile::IniFile() {
file = NULL;
activeSecName = NULL;
activeSec = NULL;
}
IniFile::IniFile(const char* file) {
setFile(file);
activeSecName = NULL;
activeSec = NULL;
}
IniFile::~IniFile() {
freeString(file);
freeString(activeSecName);
freeStringArray(activeSec);
}
void IniFile::setFile(const char* file) {
this.file = strdup(file);
}
void IniFile::setActiveSection(const char* secName) {
char* searchSection = new char[strlen(secName) + 3];
char* line = new char[MAX_CHARS + 1];
activeSec = NULL;
int numLines = 0;
ifstream inifile = new ifstream(file);
if(!inifile) {
return NULL;
}
sprintf (searchSection, "[%s]", secName);
// look for specified section
do {
inifile.getline(line, MAX_CHARS);
} while(!inifile.eof() && !inifile.fail() && strcasecmp(line,
searchSection) != 0);
while (1) {
inifile.getline(line, MAX_CHARS);
if (inifile.eof() || inifile.fail() || line[0] == '[') {
break;
}
numLines++;
activeSec = newStringArray(numLines + 1);
// (char **) realloc (activeSec, (numLines+1) * sizeof (char *));
activeSection[numLines++] = strdup(line);
// numLines++;
}
// add the NULL at the end of the dynamic array
// activeSection = (char **)realloc(activeSection, (numLines+1) * sizeof
(char *));
// activeSection[numLines] = NULL;
inifile.close();
freeStringArray(searchSection);
}
char* IniFile::getValue(char* keyword) {
char* value = NULL;
if((activeSec == NULL) || (keyword == NULL)) {
return NULL;
}
char *pName, *pValue;
// look for keyword in section
while(*activeSec) {
pName = *activeSec;
pValue = strchr(*section++, '=');
if (pValue == NULL) {
continue;
}
if (strncasecmp(pName, keyword, strlen(keyword)) == 0) {
strcpy(value, pValue + 1);
return value;
}
// checked each line, found no match; so save default
return NULL;
}
char* IniFile::getActiveSectionName() {
return strdup(activeSecName);
}
- Raw text -