ini_reader.c
Go to the documentation of this file.00001
00038 #include "ini_reader.h"
00039 #include "cfg/cfg_ini_reader.h"
00040 #include <string.h>
00041 #include <stdio.h>
00042 #include <ctype.h>
00043
00044
00045
00046
00047
00048
00049 static int findSection(KFile *fd, const char *section, size_t section_len, char *line, size_t size)
00050 {
00051 while (kfile_gets(fd, line, size) != EOF)
00052 {
00053 char *ptr = line;
00054 unsigned i;
00055
00056 if (*ptr++ != '[')
00057 continue;
00058
00059
00060 for (i = 0; i < size && *ptr != ']'; ++i, ++ptr)
00061 ;
00062
00063
00064 if (section_len != i)
00065 continue;
00066
00067
00068 if(strncmp(&line[1], section, section_len))
00069 continue;
00070 else
00071 return 0;
00072 }
00073 return EOF;
00074 }
00075
00076
00077
00078
00079 static char *getKey(const char *line, char *key, size_t size)
00080 {
00081
00082 while (isspace((unsigned char)*line))
00083 ++line;
00084 int i = 0;
00085 while (*line != '=' && !isspace((unsigned char)*line) && size)
00086 {
00087 key[i++] = *line;
00088 ++line;
00089 --size;
00090 }
00091 size ? (key[i] = '\0') : (key[i-1] = '\0');
00092 return key;
00093 }
00094
00095
00096
00097
00098 static char *getValue(const char *line, char *value, size_t size)
00099 {
00100 while (*line++ != '=')
00101 ;
00102 while (isspace((unsigned char)*line))
00103 ++line;
00104 int i = 0;
00105 while (*line && size)
00106 {
00107 value[i++] = *line++;
00108 --size;
00109 }
00110 size ? (value[i] = '\0') : (value[i-1] = '\0');
00111 return value;
00112 }
00113
00121 static int findKey(KFile *fd, const char *key, char *line, size_t size)
00122 {
00123 int err;
00124 do
00125 {
00126 err = kfile_gets(fd, line, size);
00127 char curr_key[30];
00128 getKey(line, curr_key, 30);
00129
00130 if (!strcmp(curr_key, key))
00131 return 0;
00132 }
00133 while (err != EOF && *line != '[');
00134 return EOF;
00135 }
00136
00137
00138
00139
00140 int ini_getString(KFile *fd, const char *section, const char *key, const char *default_value, char *buf, size_t size)
00141 {
00142 char line[CONFIG_INI_MAX_LINE_LEN];
00143
00144 if (kfile_seek(fd, 0, KSM_SEEK_SET) == EOF)
00145 goto error;
00146
00147 if (findSection(fd, section, strlen(section), line, CONFIG_INI_MAX_LINE_LEN) == EOF)
00148 goto error;
00149
00150 if (findKey(fd, key, line, CONFIG_INI_MAX_LINE_LEN) == EOF)
00151 goto error;
00152 else
00153 getValue(line, buf, size);
00154 return 0;
00155
00156 error:
00157 strncpy(buf, default_value, size);
00158 if (size > 0)
00159 buf[size - 1] = '\0';
00160 return EOF;
00161 }