Back to index

glibc  2.9
search.c
Go to the documentation of this file.
00001 #include <stdlib.h>
00002 #include <stdio.h>
00003 #include <string.h>
00004 
00005 /* Define an array of critters to sort. */
00006 
00007 struct critter
00008   {
00009     const char *name;
00010     const char *species;
00011   };
00012 
00013 struct critter muppets[] =
00014   {
00015     {"Kermit", "frog"},
00016     {"Piggy", "pig"},
00017     {"Gonzo", "whatever"},
00018     {"Fozzie", "bear"},
00019     {"Sam", "eagle"},
00020     {"Robin", "frog"},
00021     {"Animal", "animal"},
00022     {"Camilla", "chicken"},
00023     {"Sweetums", "monster"},
00024     {"Dr. Strangepork", "pig"},
00025     {"Link Hogthrob", "pig"},
00026     {"Zoot", "human"},
00027     {"Dr. Bunsen Honeydew", "human"},
00028     {"Beaker", "human"},
00029     {"Swedish Chef", "human"}
00030   };
00031 
00032 int count = sizeof (muppets) / sizeof (struct critter);
00033 
00034 
00035 
00036 /* This is the comparison function used for sorting and searching. */
00037 
00038 int 
00039 critter_cmp (const struct critter *c1, const struct critter *c2)
00040 {
00041   return strcmp (c1->name, c2->name);
00042 }
00043 
00044 
00045 /* Print information about a critter. */
00046 
00047 void 
00048 print_critter (const struct critter *c)
00049 {
00050   printf ("%s, the %s\n", c->name, c->species);
00051 }
00052 
00053 
00054 /*@group*/
00055 /* Do the lookup into the sorted array. */
00056 
00057 void 
00058 find_critter (const char *name)
00059 {
00060   struct critter target, *result;
00061   target.name = name;
00062   result = bsearch (&target, muppets, count, sizeof (struct critter),
00063                   critter_cmp);
00064   if (result)
00065     print_critter (result);
00066   else
00067     printf ("Couldn't find %s.\n", name);
00068 }
00069 /*@end group*/
00070 
00071 /* Main program. */
00072 
00073 int
00074 main (void)
00075 {
00076   int i;
00077 
00078   for (i = 0; i < count; i++)
00079     print_critter (&muppets[i]);
00080   printf ("\n");
00081 
00082   qsort (muppets, count, sizeof (struct critter), critter_cmp);
00083 
00084   for (i = 0; i < count; i++)
00085     print_critter (&muppets[i]);
00086   printf ("\n");
00087 
00088   find_critter ("Kermit");
00089   find_critter ("Gonzo");
00090   find_critter ("Janice");
00091 
00092   return 0;
00093 }