1*13109Srrh #ifndef lint 2*13109Srrh static char sccsid[] = "@(#)alpha.seek.c 1.2 06/14/83"; 3*13109Srrh #endif not lint 412908Sgarrison 512908Sgarrison # include "stdio.h" 612908Sgarrison # include "ctype.h" 712908Sgarrison # include "streams.h" 812908Sgarrison # define nexttry ((high+low)/2) 912908Sgarrison 1012908Sgarrison /* alpha_seek(stream, word, s_size, fold) 1112908Sgarrison seeks the first line in stream that is at least word. 1212908Sgarrison assumes that stream is a sorted file of lines. (last char must be \n) 1312908Sgarrison if fold, assumes that word is lowercase and folds stream to lowercase. 1412908Sgarrison s_size = size of stream 1512908Sgarrison returns 1 if word = line, 0 o.w. 1612908Sgarrison */ 1712908Sgarrison int alpha_seek(stream, word, s_size, fold) 1812908Sgarrison FILE *stream; 1912908Sgarrison char *word; 2012908Sgarrison long int s_size; 2112908Sgarrison int fold; 2212908Sgarrison { long int high, low, mid; /* point to beginning of a line in stream */ 2312908Sgarrison int ans; /* line(low) < word <= line(high) */ 2412908Sgarrison char line[maxstr]; 2512908Sgarrison 2612908Sgarrison 2712908Sgarrison /* initialize low (return if first line >= word) */ 2812908Sgarrison low= 0L; 2912908Sgarrison pos(low); getline(stream, line); 3012908Sgarrison if (fold) foldline(line); 3112908Sgarrison ans= strcmp(line,word); 3212908Sgarrison 3312908Sgarrison if ( ans >= 0) 3412908Sgarrison { pos(low); return(ans==0); } 3512908Sgarrison 3612908Sgarrison /* initialize high to "line" after last line */ 3712908Sgarrison high= s_size; 3812908Sgarrison 3912908Sgarrison mid= nextline(stream, nexttry ); 4012908Sgarrison while (mid < high ) 4112908Sgarrison { getline(stream,line); 4212908Sgarrison if (fold) foldline(line); 4312908Sgarrison if (strcmp(line,word) < 0) low= mid; 4412908Sgarrison else high= mid; 4512908Sgarrison mid= nextline(stream, nexttry ); 4612908Sgarrison } 4712908Sgarrison 4812908Sgarrison /* linear search from low to high */ 4912908Sgarrison low= nextline(stream,low); 5012908Sgarrison for(;;) 5112908Sgarrison { if (low>=high) break; 5212908Sgarrison 5312908Sgarrison getline(stream,line); 5412908Sgarrison if (fold) foldline(line); 5512908Sgarrison ans=strcmp(line,word); 5612908Sgarrison 5712908Sgarrison if (ans>=0) break; 5812908Sgarrison low= ftell(stream); 5912908Sgarrison } 6012908Sgarrison 6112908Sgarrison pos(low); 6212908Sgarrison if (low=high) return(0); 6312908Sgarrison else return(ans==0); 6412908Sgarrison } 6512908Sgarrison 6612908Sgarrison 6712908Sgarrison /* foldline(p): change all uppercase to lowercase in string p 6812908Sgarrison */ 6912908Sgarrison foldline(p) 7012908Sgarrison char *p; 7112908Sgarrison { for (; *p!=NULL; p++) 7212908Sgarrison { if (isupper(*p)) *p = tolower(*p); 7312908Sgarrison } 7412908Sgarrison } 75