1 /*
2 	Copyright (C) Slava Astashonok <sla@0n.ru>
3 
4 	This program is free software; you can redistribute it and/or
5 	modify it under the terms of the GNU General Public License.
6 
7 	$Id: my_getopt.c,v 1.2.2.3 2004/02/02 08:06:24 sla Exp $
8 */
9 
10 #include <common.h>
11 
12 /* getopt() */
13 #include <unistd.h>
14 
15 /* fprintf() */
16 #include <stdio.h>
17 
18 #include <my_getopt.h>
19 
20 extern char *optarg;
21 extern int optind, opterr, optopt;
22 
my_getopt(int argc,char * const argv[],struct getopt_parms parms[])23 int my_getopt(int argc, char * const argv[],
24 	struct getopt_parms parms[])
25 {
26 	int c, i, p;
27 	static int flag = 0, my_opterr = 1;
28 	static char optstring[MY_GETOPT_MAX_OPTSTR];
29 
30 	if (flag++ == 0) {
31 		p = 0; i = 0;
32 		while ((parms[i].name != 0) && (p < (MY_GETOPT_MAX_OPTSTR - 1))) {
33 			optstring[p++] = parms[i].name;
34 			if (parms[i].flag & MY_GETOPT_ARG_REQUIRED) optstring[p++] = ':';
35 			optstring[p] = 0;
36 			i++;
37 		}
38 		flag = 1;
39 	}
40 
41 	c = getopt(argc, argv, optstring);
42 	switch (c) {
43 		case '?':
44 			if (my_opterr) fprintf(stderr, "Wrong parameters\n");
45 			break;
46 
47 		case -1:
48 			flag = 0;
49 			i = 0;
50 			while (parms[i].name != 0) {
51 				if ((parms[i].flag & MY_GETOPT_REQUIRED) && (parms[i].count == 0)) {
52 					if (my_opterr) fprintf(stderr, "Missing required option\n");
53 					return '?';
54 				}
55 				i++;
56 			}
57 			break;
58 
59 		default:
60 			i = 0;
61 			while ((parms[i].name != 0) && (parms[i].name != c)) {
62 				i++;
63 			}
64 			if (parms[i].flag & MY_GETOPT_ARG_REQUIRED) {
65 				if (optarg == 0) {
66 					if (my_opterr) fprintf(stderr, "Option `-%c': %s\n",
67 							c, "require parameter");
68 					return '?';
69 				} else parms[i].arg = optarg;
70 			}
71 			if ((++parms[i].count > 1) && !(parms[i].flag & MY_GETOPT_ALLOW_REPEAT)) {
72 				if (my_opterr) fprintf(stderr, "Option `-%c': %s\n",
73 						c, "repeat not allowed");
74 				return '?';
75 			}
76 			break;
77 	}
78 	return c;
79 }
80