home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 22 gnu / 22-gnu.zip / f77cmd.zip / f77 / getopt.c < prev    next >
C/C++ Source or Header  |  1990-10-24  |  2KB  |  98 lines

  1. /* @(#)pd/getopt/getopt.c    1.2 10/24/90 05:19:06 */
  2. /*
  3.  * This file is in the public domain.
  4.  */
  5.  
  6. /*
  7.  * shell interface to the getopt(3) function for implementing a standard
  8.  * option interface.  Usage in a shell script:
  9.  *
  10.  *    set -- `getopt [-n progname] [-q] $*`
  11.  *
  12.  * -n sets the program name to use for usage messages, -q disables
  13.  * a usage message from getopt(3).  Beyond these additional flags,
  14.  * see the System V getopt(1) man page for usage instructions.
  15.  */
  16. #include <stdio.h>
  17. extern char **optarg;
  18. extern int optind, opterr;
  19.  
  20. int prevopt = 0;
  21. char *program;
  22.  
  23. main(argc, argv)
  24.     int argc;
  25.     char **argv;
  26. {
  27.     int c;
  28.     char *optstr;
  29.     int exitflag = 0;        /* != 0 ==> error encountered */
  30.  
  31.     program = *argv;
  32.  
  33.     for (;;) {
  34.         if (argc > 2 && strcmp(argv[1], "-q") == 0) {
  35.             opterr = 0;
  36.             argv++;
  37.             --argc;
  38.             continue;
  39.         }
  40.         if (argc > 2 && strncmp(argv[1], "-n", 2) == 0) {
  41.             if (argv[1][2] == '\0') {
  42.                 argv += 2;
  43.                 argc -= 2;
  44.                 program = argv[0];
  45.             } else {
  46.                 argv++;
  47.                 --argc;
  48.                 program = &argv[0][2];
  49.             }
  50.             continue;
  51.         }
  52.         break;
  53.     }
  54.     if (argc < 2) {
  55.         fprintf(stderr,
  56.             "Usage: %s [ -q ] [ -n name ] opt-string [args]\n",
  57.             argv[0]);
  58.         exit(2);
  59.     }
  60.  
  61.     optstr = *++argv;
  62.     --argc;
  63.     *argv = program;
  64.     while ((c = getopt(argc, argv, optstr)) != EOF) {
  65.         static char buf[] = "-o";
  66.  
  67.         /* catch errors for later exiting */
  68.         if (c == '?') {
  69.             exitflag = 1;
  70.         }
  71.  
  72.         /* process the arg we have found */
  73.         if (c != '?' || opterr == 0) {
  74.             buf[1] = c;
  75.             outarg(buf);
  76.         }
  77.         if (optarg) {
  78.             outarg(optarg);
  79.         }
  80.     }
  81.     outarg("--");
  82.     while (optind < argc) {
  83.         outarg(argv[optind++]);
  84.     }
  85.     putchar('\n');
  86.     exit(exitflag);
  87. }
  88.  
  89. outarg(s)
  90.     char *s;
  91. {
  92.     if (prevopt) {
  93.         putchar(' ');
  94.     }
  95.     prevopt = 1;
  96.     fputs(s, stdout);
  97. }
  98.