Name
lfind, lsearch - Performs a linear array search.
Syntax
#include <stdlib.h>
char *lfind(key, base, num, width, compare)
char *lsearch(key, base, num, width, compare)
char *key;
char *base;
unsigned *num, width;
int (*compare)(elem1, elem);
const void *elem1, *elem2;
Description
The lsearch and lfind functions perform a linear search for
the value key in an array of num elements, each of width
bytes in size. (Unlike bsearch, lsearch and lfind do not
require the array to be sorted.) The argument base is a
pointer to the base of the array to be searched.
If key is not found, lsearch adds it to the end. The lfind
function does not.
The argument compare is a pointer to a user-supplied routine
that compares two array elements and returns a value
specifying their relationship. Both lsearch and lfind call
the compare routine one or more times during the search,
passing pointers to two array elements on each call. This
routine must compare the elements, and return non-zero when
element1 and element2 are different, or return 0 (zero) when
element1 is identical to element2.
Return Value
If the key is found, both lsearch and lfind return a pointer
to the array element base that matches key . If the key is
not found, lfind returns NULL, and lsearch returns a pointer
to the newly added item at the end of the array.
See Also
bsearch(S)
Example
#include <search.h> #include <string.h> #include <stdio.h>
int compare(); /* must declare as a function */
main (argc, argv) int argc; char **argv;
{
char **result;
char *key = "PATH";
result = (char **)lfind((char *)&key, (char *)argv,
&argc,
sizeof(char *), compare);
Page 1 (printed 6/18/89)
LFIND(DOS) UNIX System V LFIND(DOS)
if (result)
printf("%s found\n", *result);
else
printf("PATH not found!\n");
}
int compare (arg1, arg2) char **arg1, **arg2;
{
return(strncmp(*arg1,*arg2,strlen(*arg1)));
}
This program uses lfind to search for the keyword PATH in
the command line arguments. Unlike lsearch, lfind fails if
the keyword is not found.
Page 2 (printed 6/18/89)