2 /*-------------------------------------------------------------------------*/
8 @brief Parser for ini files.
10 /*--------------------------------------------------------------------------*/
12 $Id: iniparser.c,v 2.19 2011-03-02 20:15:13 ndevilla Exp $
14 $Date: 2011-03-02 20:15:13 $
16 /*---------------------------- Includes ------------------------------------*/
18 #include "iniparser.h"
20 /*---------------------------- Defines -------------------------------------*/
21 #define ASCIILINESZ (1024)
22 #define INI_INVALID_KEY ((char*)-1)
24 /*---------------------------------------------------------------------------
25 Private to this module
26 ---------------------------------------------------------------------------*/
28 * This enum stores the status for each parsed line (internal use only).
30 typedef enum _line_status_ {
39 /*-------------------------------------------------------------------------*/
41 @brief Convert a string to lowercase.
42 @param s String to convert.
43 @return ptr to statically allocated string.
45 This function returns a pointer to a statically allocated string
46 containing a lowercased version of the input string. Do not free
47 or modify the returned string! Since the returned string is statically
48 allocated, it will be modified at each function call (not re-entrant).
50 /*--------------------------------------------------------------------------*/
51 static char * strlwc(char * s)
53 static char l[ASCIILINESZ+1];
56 if (s==NULL) return NULL ;
57 memset(l, 0, ASCIILINESZ+1);
59 while (s[i] && i<ASCIILINESZ) {
60 l[i] = (char)tolower((int)s[i]);
63 l[ASCIILINESZ]=(char)0;
67 /*-------------------------------------------------------------------------*/
69 @brief Remove blanks at the beginning and the end of a string.
70 @param s String to parse.
71 @return ptr to statically allocated string.
73 This function returns a pointer to a statically allocated string,
74 which is identical to the input string, except that all blank
75 characters at the end and the beg. of the string have been removed.
76 Do not free or modify the returned string! Since the returned string
77 is statically allocated, it will be modified at each function call
80 /*--------------------------------------------------------------------------*/
81 static char * strstrip(char * s)
83 static char l[ASCIILINESZ+1];
86 if (s==NULL) return NULL ;
88 while (isspace((int)*s) && *s) s++;
89 memset(l, 0, ASCIILINESZ+1);
93 if (!isspace((int)*(last-1)))
101 /*-------------------------------------------------------------------------*/
103 @brief Get number of sections in a dictionary
104 @param d Dictionary to examine
105 @return int Number of sections found in dictionary
107 This function returns the number of sections found in a dictionary.
108 The test to recognize sections is done on the string stored in the
109 dictionary: a section name is given as "section" whereas a key is
110 stored as "section:key", thus the test looks for entries that do not
113 This clearly fails in the case a section name contains a colon, but
114 this should simply be avoided.
116 This function returns -1 in case of error.
118 /*--------------------------------------------------------------------------*/
119 int iniparser_getnsec(dictionary * d)
124 if (d==NULL) return -1 ;
126 for (i=0 ; i<d->size ; i++) {
129 if (strchr(d->key[i], ':')==NULL) {
136 /*-------------------------------------------------------------------------*/
138 @brief Get name for section n in a dictionary.
139 @param d Dictionary to examine
140 @param n Section number (from 0 to nsec-1).
141 @return Pointer to char string
143 This function locates the n-th section in a dictionary and returns
144 its name as a pointer to a string statically allocated inside the
145 dictionary. Do not free or modify the returned string!
147 This function returns NULL in case of error.
149 /*--------------------------------------------------------------------------*/
150 char * iniparser_getsecname(dictionary * d, int n)
155 if (d==NULL || n<0) return NULL ;
157 for (i=0 ; i<d->size ; i++) {
160 if (strchr(d->key[i], ':')==NULL) {
172 /*-------------------------------------------------------------------------*/
174 @brief Dump a dictionary to an opened file pointer.
175 @param d Dictionary to dump.
176 @param f Opened file pointer to dump to.
179 This function prints out the contents of a dictionary, one element by
180 line, onto the provided file pointer. It is OK to specify @c stderr
181 or @c stdout as output files. This function is meant for debugging
184 /*--------------------------------------------------------------------------*/
185 void iniparser_dump(dictionary * d, FILE * f)
189 if (d==NULL || f==NULL) return ;
190 for (i=0 ; i<d->size ; i++) {
193 if (d->val[i]!=NULL) {
194 fprintf(f, "[%s]=[%s]\n", d->key[i], d->val[i]);
196 fprintf(f, "[%s]=UNDEF\n", d->key[i]);
202 /*-------------------------------------------------------------------------*/
204 @brief Save a dictionary to a loadable ini file
205 @param d Dictionary to dump
206 @param f Opened file pointer to dump to
209 This function dumps a given dictionary into a loadable ini file.
210 It is Ok to specify @c stderr or @c stdout as output files.
212 /*--------------------------------------------------------------------------*/
213 void iniparser_dump_ini(dictionary * d, FILE * f)
216 char keym[ASCIILINESZ+1];
221 if (d==NULL || f==NULL) return ;
223 nsec = iniparser_getnsec(d);
225 /* No section in file: dump all keys as they are */
226 for (i=0 ; i<d->size ; i++) {
229 fprintf(f, "%s = %s\n", d->key[i], d->val[i]);
233 for (i=0 ; i<nsec ; i++) {
234 secname = iniparser_getsecname(d, i) ;
235 seclen = (int)strlen(secname);
236 fprintf(f, "\n[%s]\n", secname);
237 sprintf(keym, "%s:", secname);
238 for (j=0 ; j<d->size ; j++) {
241 if (!strncmp(d->key[j], keym, seclen+1)) {
245 d->val[j] ? d->val[j] : "");
253 /*-------------------------------------------------------------------------*/
255 @brief Get the string associated to a key
256 @param d Dictionary to search
257 @param key Key string to look for
258 @param def Default value to return if key not found.
259 @return pointer to statically allocated character string
261 This function queries a dictionary for a key. A key as read from an
262 ini file is given as "section:key". If the key cannot be found,
263 the pointer passed as 'def' is returned.
264 The returned char pointer is pointing to a string allocated in
265 the dictionary, do not free or modify it.
267 /*--------------------------------------------------------------------------*/
268 char * iniparser_getstring(dictionary * d, char * key, char * def)
273 if (d==NULL || key==NULL)
276 lc_key = strlwc(key);
277 sval = dictionary_get(d, lc_key, def);
281 /*-------------------------------------------------------------------------*/
283 @brief Get the string associated to a key, convert to an int
284 @param d Dictionary to search
285 @param key Key string to look for
286 @param notfound Value to return in case of error
289 This function queries a dictionary for a key. A key as read from an
290 ini file is given as "section:key". If the key cannot be found,
291 the notfound value is returned.
293 Supported values for integers include the usual C notation
294 so decimal, octal (starting with 0) and hexadecimal (starting with 0x)
295 are supported. Examples:
298 "042" -> 34 (octal -> decimal)
299 "0x42" -> 66 (hexa -> decimal)
301 Warning: the conversion may overflow in various ways. Conversion is
302 totally outsourced to strtol(), see the associated man page for overflow
305 Credits: Thanks to A. Becker for suggesting strtol()
307 /*--------------------------------------------------------------------------*/
308 int iniparser_getint(dictionary * d, char * key, int notfound)
312 str = iniparser_getstring(d, key, INI_INVALID_KEY);
313 if (str==INI_INVALID_KEY) return notfound ;
314 return (int)strtol(str, NULL, 0);
317 /*-------------------------------------------------------------------------*/
319 @brief Get the string associated to a key, convert to a double
320 @param d Dictionary to search
321 @param key Key string to look for
322 @param notfound Value to return in case of error
325 This function queries a dictionary for a key. A key as read from an
326 ini file is given as "section:key". If the key cannot be found,
327 the notfound value is returned.
329 /*--------------------------------------------------------------------------*/
330 double iniparser_getdouble(dictionary * d, char * key, double notfound)
334 str = iniparser_getstring(d, key, INI_INVALID_KEY);
335 if (str==INI_INVALID_KEY) return notfound ;
339 /*-------------------------------------------------------------------------*/
341 @brief Get the string associated to a key, convert to a boolean
342 @param d Dictionary to search
343 @param key Key string to look for
344 @param notfound Value to return in case of error
347 This function queries a dictionary for a key. A key as read from an
348 ini file is given as "section:key". If the key cannot be found,
349 the notfound value is returned.
351 A true boolean is found if one of the following is matched:
353 - A string starting with 'y'
354 - A string starting with 'Y'
355 - A string starting with 't'
356 - A string starting with 'T'
357 - A string starting with '1'
359 A false boolean is found if one of the following is matched:
361 - A string starting with 'n'
362 - A string starting with 'N'
363 - A string starting with 'f'
364 - A string starting with 'F'
365 - A string starting with '0'
367 The notfound value returned if no boolean is identified, does not
368 necessarily have to be 0 or 1.
370 /*--------------------------------------------------------------------------*/
371 int iniparser_getboolean(dictionary * d, char * key, int notfound)
376 c = iniparser_getstring(d, key, INI_INVALID_KEY);
377 if (c==INI_INVALID_KEY) return notfound ;
378 if (c[0]=='y' || c[0]=='Y' || c[0]=='1' || c[0]=='t' || c[0]=='T') {
380 } else if (c[0]=='n' || c[0]=='N' || c[0]=='0' || c[0]=='f' || c[0]=='F') {
388 /*-------------------------------------------------------------------------*/
390 @brief Finds out if a given entry exists in a dictionary
391 @param ini Dictionary to search
392 @param entry Name of the entry to look for
393 @return integer 1 if entry exists, 0 otherwise
395 Finds out if a given entry exists in the dictionary. Since sections
396 are stored as keys with NULL associated values, this is the only way
397 of querying for the presence of sections in a dictionary.
399 /*--------------------------------------------------------------------------*/
400 int iniparser_find_entry(
406 if (iniparser_getstring(ini, entry, INI_INVALID_KEY)!=INI_INVALID_KEY) {
412 /*-------------------------------------------------------------------------*/
414 @brief Set an entry in a dictionary.
415 @param ini Dictionary to modify.
416 @param entry Entry to modify (entry name)
417 @param val New value to associate to the entry.
418 @return int 0 if Ok, -1 otherwise.
420 If the given entry can be found in the dictionary, it is modified to
421 contain the provided value. If it cannot be found, -1 is returned.
422 It is Ok to set val to NULL.
424 /*--------------------------------------------------------------------------*/
425 int iniparser_set(dictionary * ini, char * entry, char * val)
427 return dictionary_set(ini, strlwc(entry), val) ;
430 /*-------------------------------------------------------------------------*/
432 @brief Delete an entry in a dictionary
433 @param ini Dictionary to modify
434 @param entry Entry to delete (entry name)
437 If the given entry can be found, it is deleted from the dictionary.
439 /*--------------------------------------------------------------------------*/
440 void iniparser_unset(dictionary * ini, char * entry)
442 dictionary_unset(ini, strlwc(entry));
445 /*-------------------------------------------------------------------------*/
447 @brief Load a single line from an INI file
448 @param input_line Input line, may be concatenated multi-line input
449 @param section Output space to store section
450 @param key Output space to store key
451 @param value Output space to store value
452 @return line_status value
454 /*--------------------------------------------------------------------------*/
455 static line_status iniparser_line(
462 char line[ASCIILINESZ+1];
465 strcpy(line, strstrip(input_line));
466 len = (int)strlen(line);
468 sta = LINE_UNPROCESSED ;
472 } else if (line[0]=='#' || line[0]==';') {
475 } else if (line[0]=='[' && line[len-1]==']') {
477 sscanf(line, "[%[^]]", section);
478 strcpy(section, strstrip(section));
479 strcpy(section, strlwc(section));
481 } else if (sscanf (line, "%[^=] = \"%[^\"]\"", key, value) == 2
482 || sscanf (line, "%[^=] = '%[^\']'", key, value) == 2
483 || sscanf (line, "%[^=] = %[^;#]", key, value) == 2) {
484 /* Usual key=value, with or without comments */
485 strcpy(key, strstrip(key));
486 strcpy(key, strlwc(key));
487 strcpy(value, strstrip(value));
489 * sscanf cannot handle '' or "" as empty values
492 if (!strcmp(value, "\"\"") || (!strcmp(value, "''"))) {
496 } else if (sscanf(line, "%[^=] = %[;#]", key, value)==2
497 || sscanf(line, "%[^=] %[=]", key, value) == 2) {
504 strcpy(key, strstrip(key));
505 strcpy(key, strlwc(key));
509 /* Generate syntax error */
515 /*-------------------------------------------------------------------------*/
517 @brief Parse an ini file and return an allocated dictionary object
518 @param ininame Name of the ini file to read.
519 @return Pointer to newly allocated dictionary
521 This is the parser for ini files. This function is called, providing
522 the name of the file to be read. It returns a dictionary object that
523 should not be accessed directly, but through accessor functions
526 The returned dictionary must be freed using iniparser_freedict().
528 /*--------------------------------------------------------------------------*/
529 dictionary * iniparser_load(char * ininame)
533 char line [ASCIILINESZ+1] ;
534 char section [ASCIILINESZ+1] ;
535 char key [ASCIILINESZ+1] ;
536 char tmp [ASCIILINESZ+1] ;
537 char val [ASCIILINESZ+1] ;
546 if ((in=fopen(ininame, "r"))==NULL) {
547 fprintf(stderr, "iniparser: cannot open %s\n", ininame);
551 dict = dictionary_new(0) ;
557 memset(line, 0, ASCIILINESZ);
558 memset(section, 0, ASCIILINESZ);
559 memset(key, 0, ASCIILINESZ);
560 memset(val, 0, ASCIILINESZ);
563 while (fgets(line+last, ASCIILINESZ-last, in)!=NULL) {
565 len = (int)strlen(line)-1;
568 /* Safety check against buffer overflows */
569 if (line[len]!='\n') {
571 "iniparser: input line too long in %s (%d)\n",
574 dictionary_del(dict);
578 /* Get rid of \n and spaces at end of line */
580 ((line[len]=='\n') || (isspace(line[len])))) {
584 /* Detect multi-line */
585 if (line[len]=='\\') {
586 /* Multi-line value */
592 switch (iniparser_line(line, section, key, val)) {
598 errs = dictionary_set(dict, section, NULL);
602 sprintf(tmp, "%s:%s", section, key);
603 errs = dictionary_set(dict, tmp, val) ;
607 fprintf(stderr, "iniparser: syntax error in %s (%d):\n",
610 fprintf(stderr, "-> %s\n", line);
617 memset(line, 0, ASCIILINESZ);
620 fprintf(stderr, "iniparser: memory allocation failure\n");
625 dictionary_del(dict);
632 /*-------------------------------------------------------------------------*/
634 @brief Free all memory associated to an ini dictionary
635 @param d Dictionary to free
638 Free all memory associated to an ini dictionary.
639 It is mandatory to call this function before the dictionary object
640 gets out of the current context.
642 /*--------------------------------------------------------------------------*/
643 void iniparser_freedict(dictionary * d)
648 /* vim: set ts=4 et sw=4 tw=75 */