man(1) Manual page archive

     ARG(2)                                                     ARG(2)

          ARG - process option letters from argv

          #include <libc.h>
          ARGBEGIN {
          } ARGEND
          char *ARGF();
          char ARGC();

          extern char *argv0;

          Command-line arguments to programs (see exec(2)) are conven-
          tionally arranged as a set of options - strings beginning
          with a - (minus sign) - followed by plain arguments such as
          file names.  The ARG macros provide a convenient means for
          processing these options.  Option characters appear in
          nonempty clusters preceded by -.  After options processing
          is terminated (by an argument not starting with -, or by the
          argument -- which is then skipped, or by the argument -),
          execution resumes after the ARGEND.

          The body of a switch statement should be put between
          ARGBEGIN{ and }ARGEND; it is executed once for each option
          character (the character itself may be referenced by
          ARGC()).  If an option takes a string argument (that is, the
          rest of the current option string or if that is empty, the
          next argument), it can be referenced by ARGF().  After
          ARGEND, argv points at a zero-terminated list of the remain-
          ing argc arguments.

          ARGBEGIN also sets up argv0 to point at argv[0] (convention-
          ally the name of the program).

          This program processes arguments for a command that can take
          option b and option f, which requires an argument.

          #include <u.h>
          #include <libc.h>

          main(int argc, char *argv[])
                  char *f;

                  print("%s", argv[0]);
                  case 'b':       print(" -b"); break;
                  case 'f':       f = ARGF(); print(" -f(%s)", f?f:"no arg"); break;

     ARG(2)                                                     ARG(2)

                  default:        print(" badflag('%c')", ARGC()); break;
                  print(" %d args:", argc);
                          print(" '%s'", *argv++);
          When this program is run as
                  prog -bffile1 -r -f file2 arg1 argn
          it yields
                  prog -b -f(file1) badflag('r') -f(file2) 2 args: 'arg1' 'argn'

          ARGF() returns 0 on error.