rc

[fork] interactive rc shell
git clone https://hhvn.uk/rc
git clone git://hhvn.uk/rc
Log | Files | Refs | README | LICENSE

getopt.c (1143B)


      1 #include "rc.h"
      2 
      3 int     rc_opterr = 1;
      4 int     rc_optind = 1;
      5 int     rc_optopt;
      6 char    *rc_optarg;
      7 
      8 /* getopt routine courtesy of David Sanderson */
      9 
     10 extern int rc_getopt(int argc, char **argv, char *opts) {
     11 	static int sp = 1;
     12 	int c;
     13 	char *cp;
     14 	if (rc_optind == 0) /* reset rc_getopt() */
     15 		rc_optind = sp = 1;
     16 	if (sp == 1) {
     17 		if (rc_optind >= argc || argv[rc_optind][0] != '-' || argv[rc_optind][1] == '\0') {
     18 			return -1;
     19 		} else if (strcmp(argv[rc_optind], "--") == 0) {
     20 			rc_optind++;
     21 			return -1;
     22 		}
     23 	}
     24 	rc_optopt = c = argv[rc_optind][sp];
     25 	if (c == ':' || (cp=strchr(opts, c)) == 0) {
     26 		fprint(2, "%s: bad option: -%c\n", argv[0], c);
     27 		if (argv[rc_optind][++sp] == '\0') {
     28 			rc_optind++;
     29 			sp = 1;
     30 		}
     31 		return '?';
     32 	}
     33 	if (*++cp == ':') {
     34 		if (argv[rc_optind][sp+1] != '\0') {
     35 			rc_optarg = &argv[rc_optind++][sp+1];
     36 		} else if (++rc_optind >= argc) {
     37 			fprint(2, "%s: option requires an argument -- %c\n", argv[0], c);
     38 			sp = 1;
     39 			return '?';
     40 		} else
     41 			rc_optarg = argv[rc_optind++];
     42 		sp = 1;
     43 	} else {
     44 		if (argv[rc_optind][++sp] == '\0') {
     45 			sp = 1;
     46 			rc_optind++;
     47 		}
     48 		rc_optarg = NULL;
     49 	}
     50 	return c;
     51 }