Expert C Programming

(Jeff_L) #1

In this case, the argument processing would make the mail program think it was being asked to read
mail, not send it. Bingo! E-mail to users with an "f" as the second character of the name disappears!
The fix was a one-liner: if you're looking at the next-to-last argument for a possible "f", make sure it is
also preceded by a switch hyphen:


if ( argv[argc-1][0] == '-' ||


argv[argc-2][0] == '-' && (argv[argc-2][1] == 'f' ) )


readmail(argc, argv);


The problem was caused by bad parsing of arguments, but it was facilitated by inadequate
classification of arguments between switches and filenames. Many operating systems (e.g.,
VAX/VMS) distinguish between runtime options and other arguments (e.g., filenames) to programs,
but UNIX does not; nor does ANSI C.


Software Dogma


Shell Fumbles on Argument Parsing


The problem of inadequate argument parsing occurs in many places on UNIX. To find out
which files in a directory are links, you might enter the command:


ls -l | grep ->


This will yield the error message "Missing name for redirect", and most people will quickly
figure out that the right chevron has been interpreted by the shell as a redirection, not as an
argument to grep. They will then hide it from the shell by quotes, and try this:


ls -l | grep "->"


Still no good! The grep program looks at the starting minus sign, interprets the argument as
an unrecognized option of greater-than, and quits. The answer is to step back from "ls" and
instead use:


file -h * | grep link


Many people have been tormented by creating a file the name of which starts with a
hyphen, and then being unable to get rm to remove it. One solution in this case is to give the
entire pathname of the file, so that rm does not see a leading hyphen and try to interpret the
name as an option.

Free download pdf