Fix typo in macro name
[glibc.git] / manual / examples / search.c
blob31e9d0a1de368c2a7adf18cc1a1e29d793ab744b
1 /* Searching and Sorting Example
2 Copyright (C) 1991-2014 Free Software Foundation, Inc.
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, if not, see <http://www.gnu.org/licenses/>.
18 #include <stdlib.h>
19 #include <stdio.h>
20 #include <string.h>
22 /* Define an array of critters to sort. */
24 struct critter
26 const char *name;
27 const char *species;
30 struct critter muppets[] =
32 {"Kermit", "frog"},
33 {"Piggy", "pig"},
34 {"Gonzo", "whatever"},
35 {"Fozzie", "bear"},
36 {"Sam", "eagle"},
37 {"Robin", "frog"},
38 {"Animal", "animal"},
39 {"Camilla", "chicken"},
40 {"Sweetums", "monster"},
41 {"Dr. Strangepork", "pig"},
42 {"Link Hogthrob", "pig"},
43 {"Zoot", "human"},
44 {"Dr. Bunsen Honeydew", "human"},
45 {"Beaker", "human"},
46 {"Swedish Chef", "human"}
49 int count = sizeof (muppets) / sizeof (struct critter);
53 /* This is the comparison function used for sorting and searching. */
55 int
56 critter_cmp (const void *v1, const void *v2)
58 const struct critter *c1 = v1;
59 const struct critter *c2 = v2;
61 return strcmp (c1->name, c2->name);
65 /* Print information about a critter. */
67 void
68 print_critter (const struct critter *c)
70 printf ("%s, the %s\n", c->name, c->species);
74 /*@group*/
75 /* Do the lookup into the sorted array. */
77 void
78 find_critter (const char *name)
80 struct critter target, *result;
81 target.name = name;
82 result = bsearch (&target, muppets, count, sizeof (struct critter),
83 critter_cmp);
84 if (result)
85 print_critter (result);
86 else
87 printf ("Couldn't find %s.\n", name);
89 /*@end group*/
91 /* Main program. */
93 int
94 main (void)
96 int i;
98 for (i = 0; i < count; i++)
99 print_critter (&muppets[i]);
100 printf ("\n");
102 qsort (muppets, count, sizeof (struct critter), critter_cmp);
104 for (i = 0; i < count; i++)
105 print_critter (&muppets[i]);
106 printf ("\n");
108 find_critter ("Kermit");
109 find_critter ("Gonzo");
110 find_critter ("Janice");
112 return 0;