Skip to content

Instantly share code, notes, and snippets.

@kaworu
Created May 25, 2016 10:13
Show Gist options
  • Save kaworu/21755da8de7bac2438c9dcebeff1812c to your computer and use it in GitHub Desktop.
Save kaworu/21755da8de7bac2438c9dcebeff1812c to your computer and use it in GitHub Desktop.
#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