lfind()

Find an entry in a linear search table

Synopsis:

#include <search.h>

void * lfind( const void * key, 
              const void * base,
              unsigned * num, 
              unsigned width,
              int ( * compare)( 
              const void * element1,
              const void * element2 ) );

Arguments:

key
The object to search for.
base
A pointer to the first element in the table.
num
A pointer to an integer containing the current number of elements in the table.
width
The size of an element, in bytes.
compare
A pointer to a user-supplied function that lfind() calls to compare an array element with the key. The arguments to the comparison function are:

The comparison function must return 0 if element1 equals element2, or a nonzero value if the elements aren't equal.

Library:

libc

Use the -l c option to qcc to link against this library. This library is usually included automatically.

Description:

The lfind() function returns a pointer into a table indicating where an entry may be found.


Note: The lfind() function is the same as lsearch(), except that if the entry isn't found, it isn't added to the table, and a NULL pointer is returned.

Returns:

A pointer to the matching element, or NULL if there's no match or an error occurred.

Examples:

This example program lets you know if the first command-line argument is a C keyword (assuming you fill in the keywords array with a complete list of C keywords):

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

static const char *keywords[] = {
    "auto",
    "break",
    "case",
    "char",
    /* . */
    /* . */
    /* . */
    "while"
};

int compare( const void *, const void * );

int main( int argc, const char *argv[] )
{
    unsigned num = 5;
    char *ptr;

    if( argc <= 1 ) return EXIT_FAILURE;

    ptr = lfind( &argv[1], keywords, &num, sizeof(char **), compare );
    if( ptr == NULL ) {
        printf( "'%s' is not a C keyword\n", argv[1] );
        
        return EXIT_FAILURE;
    } else {
        printf( "'%s' is a C keyword\n", argv[1] );
        
        return EXIT_SUCCESS;
    }
    
    /* You'll never get here. */
    return EXIT_SUCCESS;
}

int compare( const void *op1, const void *op2 )
{
    const char **p1 = (const char **) op1;
    const char **p2 = (const char **) op2;

    return( strcmp( *p1, *p2 ) );
}

Classification:

POSIX 1003.1 XSI

Safety:
Cancellation point No
Interrupt handler No
Signal handler Yes
Thread Yes

See also:

bsearch(), lsearch()