Example (bsearch -- Search Arrays)

This example performs a binary search on the argv array of pointers to the program parameters and finds the position of the argument PATH. It first removes the program name from argv, and then sorts the array alphabetically before calling bsearch. The functions compare1 and compare2 compare the values pointed to by arg1 and arg2 and return the result to bsearch.

    #include <stdlib.h>
    #include <stdio.h>
    #include <string.h>

    /* -------------------------------------------------------------- */
    /* For OS/2 and Windows -- Note: Library always calls functions   */
    /*    internally with _Optlink linkage convention.  Ensure that   */
    /*    compare1() and compare2 are always _Optlink.                */
    /* -------------------------------------------------------------- */

    #if (1 == __TOS_OS2__)    /* For OS/2 */
       int _Optlink compare1(const void *arg1, const void *arg2)
    #else
       int compare1 (const void *arg1, const void *arg2) /* For Windows*/
    #endif
    {
       return (strcmp(*(char **)arg1, *(char **)arg2));
    }
    #if  (1 == __TOS_OS2__)    /* For OS/2 */
       int _Optlink compare2(const void *arg1,const void *arg2)
    #else
       int compare2 (const void *arg1, const void *arg2)
    #endif
    {
       return (strcmp((char *)arg1, *(char **)arg2));
    }
    int main(int argc,char *argv[])
    {
       char **result;
       char *key = "PATH";
       int i;
       argv++;
       argc--;
       qsort((char *)argv, argc, sizeof(char *), compare1);
       result = (char **)bsearch(key, argv, argc, sizeof(char *), compare2);
       if (result != NULL) {
          printf("result = <%s>\n", *result);
       }
       else
          printf("result is null\n");
       return 0;

       /**************************************************************
          If the program name is progname and you enter:
          progname where is PATH in this phrase?

          The output should be:

          result = <PATH>
       **************************************************************/
    }