/*ini_handle.c*/
#include <stdio.h>
#include <string.h>
#include "ini_handle.h"
/**
* Read sting type value from configure file in section
* @param section :pursuant flag
* @param key :to read property
* @param filename :to reading file
* @return reading key or NULL
*/
char *ini_get_string(char *section, char *key, char *filename)
{
FILE *fp = NULL;
char szLine[1024];
static char tmpstr[1024];
int flag = 0;
char *tmp = NULL;
char *find = NULL;
fp=fopen(filename, "r");
if (fp == NULL)
{
// DLOG("no such file: %s", filename);
printf("no such file: %s", filename);
return "";
}
while (!feof(fp))
{
memset(szLine, NULL, sizeof(szLine));
memset(tmpstr, NULL, sizeof(tmpstr));
/** read a line to szLine */
fgets(szLine, 1024, fp);
if ('#' == szLine[0])
{
continue;
}
else if(szLine[0] == NULL)
{
// DLOG("read end");
printf("read end\n");
break;
}
else if((isspace(szLine[0])) && (flag == 1))
{
// DLOG("no key: %s in section: %s", key, section);
printf("no key: %s in section: %s\n", key, section);
break;
}
else
{
tmp = strchr(szLine, '=');
}
if ((tmp != NULL) && (flag == 1))
{
if (strstr(szLine, key) != NULL)
{
strcpy(tmpstr, tmp + 1);
fclose(fp);
find = strchr(tmpstr, '\n');
if(find != NULL)
{
*find = NULL;
}
return tmpstr;
}
}
else
{
strcpy(tmpstr, "[");
strcat(tmpstr, section);
strcat(tmpstr, "]");
if (strncmp(tmpstr, szLine, strlen(tmpstr)) == 0)
{
//found section
flag = 1;
szLine[0] = '\0';
}
else
{
continue;
}
}
}
if(flag == 0)
{
// DLOG("no such section: %s", section);
printf("no such section: %s\n", section);
}
fclose(fp);
return "";
}
/**
* Read integer type value from configure file in section
* @param section :pursuant flag
* @param key :to read property
* @param filename :to reading file
* @return reading key or NULL
*/
int ini_get_int(char *section, char *key, char *filename)
{
return atoi(ini_get_string(section, key, filename));
}
#ifndef INI_HANDLE_H
#define INI_HANDLE_H
#include <stdio.h>
#include <string.h>
/**
* Read sting type value from configure file in section
* @param section :pursuant flag
* @param key :to read property
* @param filename :to reading file
* @return reading key or NULL
*/
char *ini_get_string(char *section, char *key, char *filename);
/**
* Read integer type value from configure file in section
* @param section :pursuant flag
* @param key :to read property
* @param filename :to reading file
* @return reading key or NULL
*/
int ini_get_int(char *section, char *key, char *filename);
#endif