Parsing Command-Line Arguments

June 18, 2010

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.

Pages: 1 2

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: