20.09.2015 Views

Programming in C

Kochan - ProgramminginC

Kochan - ProgramminginC

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Command-L<strong>in</strong>e Arguments<br />

381<br />

If the previous command is executed, the system automatically passes to ma<strong>in</strong> a po<strong>in</strong>ter<br />

to the character str<strong>in</strong>g "aerie" <strong>in</strong> argv[1]. Recall that argv[0] conta<strong>in</strong>s a po<strong>in</strong>ter to<br />

the name of the program, which <strong>in</strong> this case is "lookup".<br />

The ma<strong>in</strong> rout<strong>in</strong>e might appear as follows:<br />

#<strong>in</strong>clude <br />

#<strong>in</strong>clude <br />

<strong>in</strong>t ma<strong>in</strong> (<strong>in</strong>t argc, char *argv[])<br />

{<br />

const struct entry dictionary[100] =<br />

{ { "aardvark", "a burrow<strong>in</strong>g African mammal" },<br />

{ "abyss", "a bottomless pit" },<br />

{ "acumen", "mentally sharp; keen" },<br />

{ "addle", "to become confused" },<br />

{ "aerie", "a high nest" },<br />

{ "affix", "to append; attach" },<br />

{ "agar", "a jelly made from seaweed" },<br />

{ "ahoy", "a nautical call of greet<strong>in</strong>g" },<br />

{ "aigrette", "an ornamental cluster of feathers" },<br />

{ "ajar", "partially opened" } };<br />

<strong>in</strong>t entries = 10;<br />

<strong>in</strong>t entryNumber;<br />

<strong>in</strong>t lookup (const struct entry dictionary [], const char search[],<br />

const <strong>in</strong>t entries);<br />

if ( argc != 2 )<br />

{<br />

fpr<strong>in</strong>tf (stderr, "No word typed on the command l<strong>in</strong>e.\n");<br />

return EXIT_FAILURE;<br />

}<br />

entryNumber = lookup (dictionary, argv[1], entries);<br />

if ( entryNumber != -1 )<br />

pr<strong>in</strong>tf ("%s\n", dictionary[entryNumber].def<strong>in</strong>ition);<br />

else<br />

pr<strong>in</strong>tf ("Sorry, %s is not <strong>in</strong> my dictionary.\n", argv[1]);<br />

}<br />

return EXIT_SUCCESS;<br />

The ma<strong>in</strong> rout<strong>in</strong>e tests to make certa<strong>in</strong> that a word was typed after the program name<br />

when the program was executed. If it wasn’t, or if more than one word was typed, the<br />

value of argc is not equal to 2. In this case, the program writes an error message to standard<br />

error and term<strong>in</strong>ates, return<strong>in</strong>g an exit status of EXIT_FAILURE.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!