[Previous] [Contents] [Next]

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 ) );

Library:

libc

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 when the entry isn't found, it's not added to the table and a null pointer is returned.

The arguments are as follows:

key
Object to search for.
base
Points to the first element in the table.
num
Points to an integer containing the current number of elements in the table.
width
Size of an element in bytes.
compare
Points to a user-supplied function called by lfind() to compare an array element with the key. The compare function is called with key and one of the array elements as arguments.

Returns:

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

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:

Standard Unix

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

See also:

bsearch(), lsearch()


[Previous] [Contents] [Next]