Some unix systems provide a system call getopt that provides a convenient interface for programs that parse their command-line arguments in a conventional manner. getopt usually takes three arguments: a string that describes the allowable arguments, an error message to be provided to the user in the event of an invalid argument, and the list of command-line arguments (or a vector and count). The option string gives all possible options; any that take an argument are followed by a colon. For instance, for the Unix V7 diff command, the option string is "befhnmD:". The parser recognizes options with a leading dash, stops at the first argument that doesn’t start with a dash or with the "--" argument, and allows options without required arguments to be combined in a single option string; for instance, the command diff -eh -D string file1 file2 finds three options, e, h and D, including the string argument to the D option. The getopt function returns a list of option/argument pairs, with null argument for options that don’t take an argument, and a list of the remaining non-option arguements.

Your task is to write the getopt function. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.

Advertisement

Pages: 1 2