xref: /original-bsd/contrib/bib/src/alpha.seek.c (revision 00f97b5a)
1 #ifndef lint
2 static char sccsid[] = "@(#)alpha.seek.c	2.3	05/27/93";
3 #endif not lint
4 #
5 
6 # include "stdio.h"
7 # include "ctype.h"
8 # include "streams.h"
9 # define  nexttry           ((high+low)/2)
10 
11 /*  alpha_seek(stream, word, s_size, fold)
12         seeks the first line in stream that is at least word.
13     assumes that stream is a sorted file of lines.  (last char must be \n)
14     if fold, assumes that word is lowercase and folds stream to lowercase.
15     s_size = size of stream
16     returns 1 if word = line, 0 o.w.
17 */
18 int alpha_seek(stream, word, s_size, fold)
19 FILE *stream;
20 char *word;
21 long int s_size;
22 int  fold;
23 {   long int high, low, mid;    /*  point to beginning of a line in stream  */
24     int      ans;               /*  line(low) < word <= line(high)          */
25     char     line[maxstr];
26 
27 
28     /*  initialize low (return if first line >= word)       */
29         low= 0L;
30         pos(low); getline(stream, line);
31         if (fold) foldline(line);
32         ans= strcmp(line,word);
33 
34         if ( ans >= 0)
35         {   pos(low);   return(ans==0); }
36 
37     /*  initialize high to "line" after last line           */
38         high= s_size;
39 
40     mid= nextline(stream, nexttry );
41     while (mid < high )
42     {   getline(stream,line);
43         if (fold) foldline(line);
44         if (strcmp(line,word) < 0)    low=  mid;
45         else                          high= mid;
46         mid= nextline(stream, nexttry );
47     }
48 
49     /* linear search from low to high   */
50         low= nextline(stream,low);
51         for(;;)
52         {   if (low>=high)      break;
53 
54             getline(stream,line);
55             if (fold) foldline(line);
56             ans=strcmp(line,word);
57 
58             if (ans>=0)         break;
59             low= ftell(stream);
60         }
61 
62     pos(low);
63     if (low==high)  return(0);
64     else            return(ans==0);
65 }
66 
67 
68 /*  foldline(p):    change all uppercase to lowercase in string p
69 */
70 foldline(p)
71 char *p;
72 {   for (; *p!=NULL;  p++)
73     {   if (isupper(*p))    *p = tolower(*p);
74     }
75 }
76