-
-
Save kaworu/21755da8de7bac2438c9dcebeff1812c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <err.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#define NELEM(x) (sizeof(x) / sizeof(*(x))) | |
// MUST be sorted | |
const char *haystack[] = { | |
"bar", | |
"foo", | |
"oni", | |
}; | |
int | |
strcmp_wrap(const void * a, const void *b) | |
{ | |
const char *x = *((const char **)a); | |
const char *y = *((const char **)b); | |
return (strcmp(x, y)); | |
} | |
int | |
main(int argc, char **argv) | |
{ | |
if (argc != 2) | |
errx(EXIT_FAILURE, "usage %s KEY", argv[0]); | |
const char *needle = argv[1]; | |
const char *found = bsearch(&needle, haystack, NELEM(haystack), | |
sizeof(*haystack), strcmp_wrap); | |
if (found) | |
(void)printf("I CAN HAZ %s.\n", needle); | |
else | |
(void)printf("I CAN NOT HAZ %s.\n", needle); | |
return (found ? EXIT_SUCCESS : EXIT_FAILURE); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment