ViaThinkSoft CodeLib
This article is in:
CodeLib → Programming aids → C / C++
#include <iostream>
bool getIniValue(const char* fileContents, const char* section, const char* keyname, char* argOutput, size_t argMaxOutLength) {
size_t iTmp;
char *tmpFileContents, *tmpSection, *tmpStart, *tmpStart2, *tmpEnd, *tmpKeyname, *tmpStart3, *tmpStart4;
// Prepare the input file contents to make it easier parse-able
iTmp = strlen(fileContents) + strlen("\n\n[");
tmpFileContents = (char*)malloc(iTmp + 1);
if (tmpFileContents == NULL) return false;
sprintf(tmpFileContents, "\n%s\n[", fileContents);
for (iTmp = 0; iTmp < strlen(tmpFileContents); iTmp++) {
if (tmpFileContents[iTmp] == '\r') tmpFileContents[iTmp] = '\n';
}
// Find the section begin
iTmp = strlen(section) + strlen("\n[]\n");
tmpSection = (char*)malloc(iTmp + 1);
if (tmpSection == NULL) return false;
sprintf(tmpSection, "\n[%s]\n", section);
tmpStart = strstr(tmpFileContents, tmpSection);
if (tmpStart == NULL) return false;
tmpStart += iTmp;
// Find the end of the section and set a NULL terminator to it
iTmp = strlen(tmpStart) + strlen("\n");
tmpStart2 = (char*)malloc(iTmp + 1/*NUL byte*/);
if (tmpStart2 == NULL) return false;
sprintf(tmpStart2, "\n%s", tmpStart);
tmpEnd = strstr(tmpStart2, "\n[");
if (tmpEnd == NULL) return false;
tmpEnd[0] = '\0';
// Find the start of the value
iTmp = strlen(keyname) + strlen("\n=");
tmpKeyname = (char*)malloc(iTmp + 1/*NUL byte*/);
if (tmpKeyname == NULL) return false;
sprintf(tmpKeyname, "\n%s=", keyname);
tmpStart3 = strstr(tmpStart2, tmpKeyname);
if (tmpStart3 == NULL) return false;
tmpStart3 += strlen("\n");
tmpStart4 = strstr(tmpStart3, "=");
if (tmpStart4 == NULL) return false;
tmpStart4 += strlen("=");
// Find the end of the value
tmpEnd = strstr(tmpStart4, "\n");
if (tmpEnd == NULL) return false;
tmpEnd[0] = '\0';
// Copy to output
if (strlen(tmpStart4) < argMaxOutLength + 1) argMaxOutLength = strlen(tmpStart4) + 1;
memcpy(argOutput, tmpStart4, argMaxOutLength);
argOutput[argMaxOutLength - 1] = '\0';
// Free all temporary stuff
//for (iTmp = 0; iTmp < strlen(tmpFileContents); iTmp++) tmpFileContents[iTmp] = '\0';
free(tmpFileContents);
//for (iTmp = 0; iTmp < strlen(tmpSection); iTmp++) tmpSection[iTmp] = '\0';
free(tmpSection);
//for (iTmp = 0; iTmp < strlen(tmpKeyname); iTmp++) tmpKeyname[iTmp] = '\0';
free(tmpKeyname);
//for (iTmp = 0; iTmp < strlen(tmpStart2); iTmp++) tmpStart2[iTmp] = '\0';
free(tmpStart2);
// Return success
return true;
}
int main()
{
const char* fileContents = "[xxx]\nA=aaa\nB=bbb\nC=ccc\n\r\n[yyy]\r\nD=ddd\nE=eee\nF=fff\n[zzz]\nG=ggg\n";
const char* section = "yyy";
const char* keyname = "E";
size_t argMaxOutLength = 100;
char* argOutput = (char*)malloc(argMaxOutLength);
if (argOutput && getIniValue(fileContents, section, keyname, argOutput, argMaxOutLength)) {
printf(argOutput);
return 0;
}
else {
printf("ERROR\n");
return 1;
}
}
Daniel Marschall
ViaThinkSoft Co-Founder
ViaThinkSoft Co-Founder