Programming in C

(Barry) #1
Command-Line Arguments 381

If the previous command is executed, the system automatically passes to maina point-
er to the character string "aerie"in argv[1]. Recall that argv[0]contains a pointer to
the name of the program, which in this case is "lookup".
The mainroutine might appear as follows:


#include <stdlib.h>
#include <stdio.h>


int main (int argc, char *argv[])
{
const struct entry dictionary[100] =
{ { "aardvark", "a burrowing African mammal" },
{ "abyss", "a bottomless pit" },
{ "acumen", "mentally sharp; keen" },
{ "addle", "to become confused" },
{ "aerie", "a high nest" },
{ "affix", "to append; attach" },
{ "agar", "a jelly made from seaweed" },
{ "ahoy", "a nautical call of greeting" },
{ "aigrette", "an ornamental cluster of feathers" },
{ "ajar", "partially opened" } };


int entries = 10;
int entryNumber;
int lookup (const struct entry dictionary [], const char search[],
const int entries);

if ( argc != 2 )
{
fprintf (stderr, "No word typed on the command line.\n");
return EXIT_FAILURE;
}

entryNumber = lookup (dictionary, argv[1], entries);

if ( entryNumber != -1 )
printf ("%s\n", dictionary[entryNumber].definition);
else
printf ("Sorry, %s is not in my dictionary.\n", argv[1]);

return EXIT_SUCCESS;
}


The mainroutine tests to make certain that a word was typed after the program name
when the program was executed. If it wasn’t, or if more than one word was typed, the
val ue of argcis not equal to 2. In this case, the program writes an error message to stan-
dard error and terminates, returning an exit status of EXIT_FAILURE.

Free download pdf