Updated to fedora-glibc-20050415T0909
[glibc.git] / manual / examples / search.c
blob182e6e4a3fa1f684eb803bbf44adc8ebc7318283
1 #include <stdlib.h>
2 #include <stdio.h>
3 #include <string.h>
5 /* Define an array of critters to sort. */
7 struct critter
9 const char *name;
10 const char *species;
13 struct critter muppets[] =
15 {"Kermit", "frog"},
16 {"Piggy", "pig"},
17 {"Gonzo", "whatever"},
18 {"Fozzie", "bear"},
19 {"Sam", "eagle"},
20 {"Robin", "frog"},
21 {"Animal", "animal"},
22 {"Camilla", "chicken"},
23 {"Sweetums", "monster"},
24 {"Dr. Strangepork", "pig"},
25 {"Link Hogthrob", "pig"},
26 {"Zoot", "human"},
27 {"Dr. Bunsen Honeydew", "human"},
28 {"Beaker", "human"},
29 {"Swedish Chef", "human"}
32 int count = sizeof (muppets) / sizeof (struct critter);
36 /* This is the comparison function used for sorting and searching. */
38 int
39 critter_cmp (const struct critter *c1, const struct critter *c2)
41 return strcmp (c1->name, c2->name);
45 /* Print information about a critter. */
47 void
48 print_critter (const struct critter *c)
50 printf ("%s, the %s\n", c->name, c->species);
54 /*@group*/
55 /* Do the lookup into the sorted array. */
57 void
58 find_critter (const char *name)
60 struct critter target, *result;
61 target.name = name;
62 result = bsearch (&target, muppets, count, sizeof (struct critter),
63 critter_cmp);
64 if (result)
65 print_critter (result);
66 else
67 printf ("Couldn't find %s.\n", name);
69 /*@end group*/
71 /* Main program. */
73 int
74 main (void)
76 int i;
78 for (i = 0; i < count; i++)
79 print_critter (&muppets[i]);
80 printf ("\n");
82 qsort (muppets, count, sizeof (struct critter), critter_cmp);
84 for (i = 0; i < count; i++)
85 print_critter (&muppets[i]);
86 printf ("\n");
88 find_critter ("Kermit");
89 find_critter ("Gonzo");
90 find_critter ("Janice");
92 return 0;