Syntax
#include <search.h> char *lfind(char *search_key, char *base, unsigned int *num, unsigned int *width, int (*compare)(const void *key, const void *element)); char *lsearch(char *search_key, char *base, unsigned int *num, unsigned int *width, int (*compare)(const void *key, const void *element));Description
lfind and lsearch perform a linear search for the value search_key in an array of num elements, each of width bytes in size. Unlike bsearch, lsearch and lfind do not require that you sort the array first. The argument base points to the base of the array to be searched.
If lsearch does not find the search_key, it adds the search_key to the end of the array and increments num by one. If lfind does not find the search_key, it does not add the search_key to the array.
The compare argument is a pointer to a function you must supply that takes a pointer to the key argument and to an array element, in that order. Both lfind and lsearch call this function one or more times during the search. The function must compare the key and the element and return one of the following values:
Value
Note: In earlier releases of C Set ++, lfind and lsearch began with an underscore (_lfind and _lsearch). Because they are defined by the X/Open standard, the underscore has been removed. For compatibility, The Developer's Toolkit will map _lfind and _lsearch to lfind and lsearch for you.
If search_key is found, both lsearch and lfind return a pointer to that element of the array to which base points. If search_key is not found, lsearch returns a pointer to a newly added item at the end of the array, while lfind returns NULL.
#include <search.h>#include <string.h> #include <stdio.h> #define CNT 2 int compare(const void *arg1,const void *arg2) { return (strncmp(*(char **)arg1, *(char **)arg2, strlen(*(char **)arg1))); } int main(void) { char **result; char *key = "PATH"; unsigned int num = CNT; char *string[CNT] = { "PATH = d:\\david\\matthew\\heather\\ed\\simon","LIB = PATH\\abc" }; /* The following statement finds the argument that starts with "PATH" */ if ((result = (char **)lfind((char *)&key, (char *)string, &num, sizeof(char *), compare)) != NULL) printf("%s found\n", *result); else printf("PATH not found \n"); return 0; /**************************************************************************** The output should be: PATH = d:\david\matthew\heather\ed\simon found ****************************************************************************/ }Related Information