iniparser.c
上传用户:xmlhyy
上传日期:2007-07-28
资源大小:20k
文件大小:15k
源码类别:

Linux/Unix编程

开发平台:

Unix_Linux

  1. /*-------------------------------------------------------------------------*/
  2. /**
  3.    @file    iniparser.c
  4.    @author  N. Devillard
  5.    @date    Mar 2000
  6.    @version $Revision: 2.14 $
  7.    @brief   Parser for ini files.
  8. */
  9. /*--------------------------------------------------------------------------*/
  10. /*
  11.     $Id: iniparser.c,v 2.14 2002/12/12 10:49:01 ndevilla Exp $
  12.     $Author: ndevilla $
  13.     $Date: 2002/12/12 10:49:01 $
  14.     $Revision: 2.14 $
  15. */
  16. /*---------------------------------------------------------------------------
  17.                                 Includes
  18.  ---------------------------------------------------------------------------*/
  19. #include "iniparser.h"
  20. #include "strlib.h"
  21. #define ASCIILINESZ         1024
  22. #define INI_INVALID_KEY     ((char*)-1)
  23. /*---------------------------------------------------------------------------
  24.                         Private to this module
  25.  ---------------------------------------------------------------------------*/
  26. /* Private: add an entry to the dictionary */
  27. static void iniparser_add_entry(
  28.     dictionary * d,
  29.     char * sec,
  30.     char * key,
  31.     char * val)
  32. {
  33.     char longkey[2*ASCIILINESZ+1];
  34.     /* Make a key as section:keyword */
  35.     if (key!=NULL) {
  36.         sprintf(longkey, "%s:%s", sec, key);
  37.     } else {
  38.         strcpy(longkey, sec);
  39.     }
  40.     /* Add (key,val) to dictionary */
  41.     dictionary_set(d, longkey, val);
  42.     return ;
  43. }
  44. /*-------------------------------------------------------------------------*/
  45. /**
  46.   @brief    Get number of sections in a dictionary
  47.   @param    d   Dictionary to examine
  48.   @return   int Number of sections found in dictionary
  49.   This function returns the number of sections found in a dictionary.
  50.   The test to recognize sections is done on the string stored in the
  51.   dictionary: a section name is given as "section" whereas a key is
  52.   stored as "section:key", thus the test looks for entries that do not
  53.   contain a colon.
  54.   This clearly fails in the case a section name contains a colon, but
  55.   this should simply be avoided.
  56.   This function returns -1 in case of error.
  57.  */
  58. /*--------------------------------------------------------------------------*/
  59. int iniparser_getnsec(dictionary * d)
  60. {
  61.     int i ;
  62.     int nsec ;
  63.     if (d==NULL) return -1 ;
  64.     nsec=0 ;
  65.     for (i=0 ; i<d->size ; i++) {
  66.         if (d->key[i]==NULL)
  67.             continue ;
  68.         if (strchr(d->key[i], ':')==NULL) {
  69.             nsec ++ ;
  70.         }
  71.     }
  72.     return nsec ;
  73. }
  74. /*-------------------------------------------------------------------------*/
  75. /**
  76.   @brief    Get name for section n in a dictionary.
  77.   @param    d   Dictionary to examine
  78.   @param    n   Section number (from 0 to nsec-1).
  79.   @return   Pointer to char string
  80.   This function locates the n-th section in a dictionary and returns
  81.   its name as a pointer to a string statically allocated inside the
  82.   dictionary. Do not free or modify the returned string!
  83.   This function returns NULL in case of error.
  84.  */
  85. /*--------------------------------------------------------------------------*/
  86. char * iniparser_getsecname(dictionary * d, int n)
  87. {
  88.     int i ;
  89.     int foundsec ;
  90.     if (d==NULL || n<0) return NULL ;
  91.     foundsec=0 ;
  92.     for (i=0 ; i<d->size ; i++) {
  93.         if (d->key[i]==NULL)
  94.             continue ;
  95.         if (strchr(d->key[i], ':')==NULL) {
  96.             foundsec++ ;
  97.             if (foundsec>n)
  98.                 break ;
  99.         }
  100.     }
  101.     if (foundsec<=n) {
  102.         return NULL ;
  103.     }
  104.     return d->key[i] ;
  105. }
  106. /*-------------------------------------------------------------------------*/
  107. /**
  108.   @brief    Dump a dictionary to an opened file pointer.
  109.   @param    d   Dictionary to dump.
  110.   @param    f   Opened file pointer to dump to.
  111.   @return   void
  112.   This function prints out the contents of a dictionary, one element by
  113.   line, onto the provided file pointer. It is OK to specify @c stderr
  114.   or @c stdout as output files. This function is meant for debugging
  115.   purposes mostly.
  116.  */
  117. /*--------------------------------------------------------------------------*/
  118. void iniparser_dump(dictionary * d, FILE * f)
  119. {
  120.     int     i ;
  121.     if (d==NULL || f==NULL) return ;
  122.     for (i=0 ; i<d->size ; i++) {
  123.         if (d->key[i]==NULL)
  124.             continue ;
  125.         if (d->val[i]!=NULL) {
  126.             fprintf(f, "[%s]=[%s]n", d->key[i], d->val[i]);
  127.         } else {
  128.             fprintf(f, "[%s]=UNDEFn", d->key[i]);
  129.         }
  130.     }
  131.     return ;
  132. }
  133. /*-------------------------------------------------------------------------*/
  134. /**
  135.   @brief    Save a dictionary to a loadable ini file
  136.   @param    d   Dictionary to dump
  137.   @param    f   Opened file pointer to dump to
  138.   @return   void
  139.   This function dumps a given dictionary into a loadable ini file.
  140.   It is Ok to specify @c stderr or @c stdout as output files.
  141.  */
  142. /*--------------------------------------------------------------------------*/
  143. void iniparser_dump_ini(dictionary * d, FILE * f)
  144. {
  145.     int     i, j ;
  146.     char    keym[ASCIILINESZ+1];
  147.     int     nsec ;
  148.     char *  secname ;
  149.     int     seclen ;
  150.     if (d==NULL || f==NULL) return ;
  151.     nsec = iniparser_getnsec(d);
  152.     if (nsec<1) {
  153.         /* No section in file: dump all keys as they are */
  154.         for (i=0 ; i<d->size ; i++) {
  155.             if (d->key[i]==NULL)
  156.                 continue ;
  157.             fprintf(f, "%s = %sn", d->key[i], d->val[i]);
  158.         }
  159.         return ;
  160.     }
  161.     for (i=0 ; i<nsec ; i++) {
  162.         secname = iniparser_getsecname(d, i) ;
  163.         seclen  = (int)strlen(secname);
  164.         fprintf(f, "n[%s]n", secname);
  165.         sprintf(keym, "%s:", secname);
  166.         for (j=0 ; j<d->size ; j++) {
  167.             if (d->key[j]==NULL)
  168.                 continue ;
  169.             if (!strncmp(d->key[j], keym, seclen+1)) {
  170.                 fprintf(f,
  171.                         "%-30s = %sn",
  172.                         d->key[j]+seclen+1,
  173.                         d->val[j] ? d->val[j] : "");
  174.             }
  175.         }
  176.     }
  177.     fprintf(f, "n");
  178.     return ;
  179. }
  180. /*-------------------------------------------------------------------------*/
  181. /**
  182.   @brief Get the string associated to a key, return NULL if not found
  183.   @param    d   Dictionary to search
  184.   @param    key Key string to look for
  185.   @return   pointer to statically allocated character string, or NULL.
  186.   This function queries a dictionary for a key. A key as read from an
  187.   ini file is given as "section:key". If the key cannot be found,
  188.   NULL is returned.
  189.   The returned char pointer is pointing to a string allocated in
  190.   the dictionary, do not free or modify it.
  191.   This function is only provided for backwards compatibility with 
  192.   previous versions of iniparser. It is recommended to use
  193.   iniparser_getstring() instead.
  194.  */
  195. /*--------------------------------------------------------------------------*/
  196. char * iniparser_getstr(dictionary * d, char * key)
  197. {
  198.     return iniparser_getstring(d, key, NULL);
  199. }
  200. /*-------------------------------------------------------------------------*/
  201. /**
  202.   @brief    Get the string associated to a key
  203.   @param    d       Dictionary to search
  204.   @param    key     Key string to look for
  205.   @param    def     Default value to return if key not found.
  206.   @return   pointer to statically allocated character string
  207.   This function queries a dictionary for a key. A key as read from an
  208.   ini file is given as "section:key". If the key cannot be found,
  209.   the pointer passed as 'def' is returned.
  210.   The returned char pointer is pointing to a string allocated in
  211.   the dictionary, do not free or modify it.
  212.  */
  213. /*--------------------------------------------------------------------------*/
  214. char * iniparser_getstring(dictionary * d, char * key, char * def)
  215. {
  216.     char * lc_key ;
  217.     char * sval ;
  218.     if (d==NULL || key==NULL)
  219.         return def ;
  220.     lc_key = strdup(strlwc(key));
  221.     sval = dictionary_get(d, lc_key, def);
  222.     free(lc_key);
  223.     return sval ;
  224. }
  225. /*-------------------------------------------------------------------------*/
  226. /**
  227.   @brief    Get the string associated to a key, convert to an int
  228.   @param    d Dictionary to search
  229.   @param    key Key string to look for
  230.   @param    notfound Value to return in case of error
  231.   @return   integer
  232.   This function queries a dictionary for a key. A key as read from an
  233.   ini file is given as "section:key". If the key cannot be found,
  234.   the notfound value is returned.
  235.  */
  236. /*--------------------------------------------------------------------------*/
  237. int iniparser_getint(dictionary * d, char * key, int notfound)
  238. {
  239.     char    *   str ;
  240.     str = iniparser_getstring(d, key, INI_INVALID_KEY);
  241.     if (str==INI_INVALID_KEY) return notfound ;
  242.     return atoi(str);
  243. }
  244. /*-------------------------------------------------------------------------*/
  245. /**
  246.   @brief    Get the string associated to a key, convert to a double
  247.   @param    d Dictionary to search
  248.   @param    key Key string to look for
  249.   @param    notfound Value to return in case of error
  250.   @return   double
  251.   This function queries a dictionary for a key. A key as read from an
  252.   ini file is given as "section:key". If the key cannot be found,
  253.   the notfound value is returned.
  254.  */
  255. /*--------------------------------------------------------------------------*/
  256. double iniparser_getdouble(dictionary * d, char * key, double notfound)
  257. {
  258.     char    *   str ;
  259.     str = iniparser_getstring(d, key, INI_INVALID_KEY);
  260.     if (str==INI_INVALID_KEY) return notfound ;
  261.     return atof(str);
  262. }
  263. /*-------------------------------------------------------------------------*/
  264. /**
  265.   @brief    Get the string associated to a key, convert to a boolean
  266.   @param    d Dictionary to search
  267.   @param    key Key string to look for
  268.   @param    notfound Value to return in case of error
  269.   @return   integer
  270.   This function queries a dictionary for a key. A key as read from an
  271.   ini file is given as "section:key". If the key cannot be found,
  272.   the notfound value is returned.
  273.   A true boolean is found if one of the following is matched:
  274.   - A string starting with 'y'
  275.   - A string starting with 'Y'
  276.   - A string starting with 't'
  277.   - A string starting with 'T'
  278.   - A string starting with '1'
  279.   A false boolean is found if one of the following is matched:
  280.   - A string starting with 'n'
  281.   - A string starting with 'N'
  282.   - A string starting with 'f'
  283.   - A string starting with 'F'
  284.   - A string starting with '0'
  285.   The notfound value returned if no boolean is identified, does not
  286.   necessarily have to be 0 or 1.
  287.  */
  288. /*--------------------------------------------------------------------------*/
  289. int iniparser_getboolean(dictionary * d, char * key, int notfound)
  290. {
  291.     char    *   c ;
  292.     int         ret ;
  293.     c = iniparser_getstring(d, key, INI_INVALID_KEY);
  294.     if (c==INI_INVALID_KEY) return notfound ;
  295.     if (c[0]=='y' || c[0]=='Y' || c[0]=='1' || c[0]=='t' || c[0]=='T') {
  296.         ret = 1 ;
  297.     } else if (c[0]=='n' || c[0]=='N' || c[0]=='0' || c[0]=='f' || c[0]=='F') {
  298.         ret = 0 ;
  299.     } else {
  300.         ret = notfound ;
  301.     }
  302.     return ret;
  303. }
  304. /*-------------------------------------------------------------------------*/
  305. /**
  306.   @brief    Finds out if a given entry exists in a dictionary
  307.   @param    ini     Dictionary to search
  308.   @param    entry   Name of the entry to look for
  309.   @return   integer 1 if entry exists, 0 otherwise
  310.   Finds out if a given entry exists in the dictionary. Since sections
  311.   are stored as keys with NULL associated values, this is the only way
  312.   of querying for the presence of sections in a dictionary.
  313.  */
  314. /*--------------------------------------------------------------------------*/
  315. int iniparser_find_entry(
  316.     dictionary  *   ini,
  317.     char        *   entry
  318. )
  319. {
  320.     int found=0 ;
  321.     if (iniparser_getstring(ini, entry, INI_INVALID_KEY)!=INI_INVALID_KEY) {
  322.         found = 1 ;
  323.     }
  324.     return found ;
  325. }
  326. /*-------------------------------------------------------------------------*/
  327. /**
  328.   @brief    Set an entry in a dictionary.
  329.   @param    ini     Dictionary to modify.
  330.   @param    entry   Entry to modify (entry name)
  331.   @param    val     New value to associate to the entry.
  332.   @return   int 0 if Ok, -1 otherwise.
  333.   If the given entry can be found in the dictionary, it is modified to
  334.   contain the provided value. If it cannot be found, -1 is returned.
  335.   It is Ok to set val to NULL.
  336.  */
  337. /*--------------------------------------------------------------------------*/
  338. int iniparser_setstr(dictionary * ini, char * entry, char * val)
  339. {
  340.     dictionary_set(ini, strlwc(entry), val);
  341.     return 0 ;
  342. }
  343. /*-------------------------------------------------------------------------*/
  344. /**
  345.   @brief    Delete an entry in a dictionary
  346.   @param    ini     Dictionary to modify
  347.   @param    entry   Entry to delete (entry name)
  348.   @return   void
  349.   If the given entry can be found, it is deleted from the dictionary.
  350.  */
  351. /*--------------------------------------------------------------------------*/
  352. void iniparser_unset(dictionary * ini, char * entry)
  353. {
  354.     dictionary_unset(ini, strlwc(entry));
  355. }
  356. /*-------------------------------------------------------------------------*/
  357. /**
  358.   @brief    Parse an ini file and return an allocated dictionary object
  359.   @param    ininame Name of the ini file to read.
  360.   @return   Pointer to newly allocated dictionary
  361.   This is the parser for ini files. This function is called, providing
  362.   the name of the file to be read. It returns a dictionary object that
  363.   should not be accessed directly, but through accessor functions
  364.   instead.
  365.   The returned dictionary must be freed using iniparser_freedict().
  366.  */
  367. /*--------------------------------------------------------------------------*/
  368. dictionary * iniparser_load(char * ininame)
  369. {
  370.     dictionary  *   d ;
  371.     char        lin[ASCIILINESZ+1];
  372.     char        sec[ASCIILINESZ+1];
  373.     char        key[ASCIILINESZ+1];
  374.     char        val[ASCIILINESZ+1];
  375.     char    *   where ;
  376.     FILE    *   ini ;
  377.     int         lineno ;
  378.     if ((ini=fopen(ininame, "r"))==NULL) {
  379.         return NULL ;
  380.     }
  381.     sec[0]=0;
  382.     /*
  383.      * Initialize a new dictionary entry
  384.      */
  385.     d = dictionary_new(0);
  386.     lineno = 0 ;
  387.     while (fgets(lin, ASCIILINESZ, ini)!=NULL) {
  388.         lineno++ ;
  389.         where = strskp(lin); /* Skip leading spaces */
  390.         if (*where==';' || *where=='#' || *where==0)
  391.             continue ; /* Comment lines */
  392.         else {
  393.             if (sscanf(where, "[%[^]]", sec)==1) {
  394.                 /* Valid section name */
  395.                 strcpy(sec, strlwc(sec));
  396.                 iniparser_add_entry(d, sec, NULL, NULL);
  397.             } else if (sscanf (where, "%[^=] = "%[^"]"", key, val) == 2
  398.                    ||  sscanf (where, "%[^=] = '%[^']'",   key, val) == 2
  399.                    ||  sscanf (where, "%[^=] = %[^;#]",     key, val) == 2) {
  400.                 strcpy(key, strlwc(strcrop(key)));
  401.                 /*
  402.                  * sscanf cannot handle "" or '' as empty value,
  403.                  * this is done here
  404.                  */
  405.                 if (!strcmp(val, """") || !strcmp(val, "''")) {
  406.                     val[0] = (char)0;
  407.                 } else {
  408.                     strcpy(val, strcrop(val));
  409.                 }
  410.                 iniparser_add_entry(d, sec, key, val);
  411.             }
  412.         }
  413.     }
  414.     fclose(ini);
  415.     return d ;
  416. }
  417. /*-------------------------------------------------------------------------*/
  418. /**
  419.   @brief    Free all memory associated to an ini dictionary
  420.   @param    d Dictionary to free
  421.   @return   void
  422.   Free all memory associated to an ini dictionary.
  423.   It is mandatory to call this function before the dictionary object
  424.   gets out of the current context.
  425.  */
  426. /*--------------------------------------------------------------------------*/
  427. void iniparser_freedict(dictionary * d)
  428. {
  429.     dictionary_del(d);
  430. }
  431. /* vim: set ts=4 et sw=4 tw=75 */