Azinix

getopt.c

Go to the documentation of this file.
00001 /**  \file getopt.c
00002  *  \brief Get options from argv
00003  */
00004 
00005 #include <stdio.h>
00006 #include "util.h"
00007 
00008 char *util_optarg;      /* Global argument pointer. */
00009 int util_optind = 0;        /* Global argv index. */
00010 static char *scan;
00011 
00012 void
00013 util_getopt_reset ()
00014 {
00015   util_optarg = 0;
00016   util_optind = 0;
00017   scan = 0;
00018 }
00019 
00020 int
00021 util_getopt (int argc, char **argv, char *optstring)
00022 {
00023   int c;
00024   char *place;
00025 
00026   util_optarg = NIL (char);
00027 
00028   if (scan == NIL (char) || *scan == '\0')
00029     {
00030       if (util_optind == 0)
00031     {
00032       util_optind++;
00033     }
00034       if (util_optind >= argc)
00035     {
00036       return EOF;
00037     }
00038       place = argv[util_optind];
00039       if ((place[0] != '-') || (place[1] == '\0'))
00040     {
00041       return EOF;
00042     }
00043       util_optind++;
00044       if ((place[1] == '-') && (place[2] == '\0'))
00045     {
00046       return EOF;
00047     }
00048       scan = place + 1;
00049     }
00050 
00051   c = *scan++;
00052   place = strchr (optstring, c);
00053   if ((place == NIL (char)) || (c == ':'))
00054     {
00055       fprintf (stderr, "%s: unknown option %c\n", argv[0], c);
00056       return '?';
00057     }
00058   if (*++place == ':')
00059     {
00060       if (*scan != '\0')
00061     {
00062       util_optarg = scan;
00063       scan = NIL (char);
00064     }
00065       else
00066     {
00067       if (util_optind >= argc)
00068         {
00069           (void) fprintf (stderr, "%s: %c requires an argument\n",
00070                   argv[0], c);
00071           return '?';
00072         }
00073       util_optarg = argv[util_optind];
00074       util_optind++;
00075     }
00076     }
00077   return c;
00078 }
00079 
00080 /*---------------------------------------------------------------------------*/
00081 /* Static function prototypes                                                */
00082 /*---------------------------------------------------------------------------*/
00083 
00084 
00085 
00086 /*---------------------------------------------------------------------------*/
00087 /* Static function prototypes                                                */
00088 /*---------------------------------------------------------------------------*/
00089 
00090 
00091 
00092 /*---------------------------------------------------------------------------*/
00093 /* Static function prototypes                                                */
00094 /*---------------------------------------------------------------------------*/