|
|
1.1 root 1: #
2:
3: # include "stdio.h"
4: # include "ctype.h"
5: # include "streams.h"
6: # define nexttry ((high+low)/2)
7:
8: /* alpha_seek(stream, word, s_size, fold)
9: seeks the first line in stream that is at least word.
10: assumes that stream is a sorted file of lines. (last char must be \n)
11: if fold, assumes that word is lowercase and folds stream to lowercase.
12: s_size = size of stream
13: returns 1 if word = line, 0 o.w.
14: */
15: int alpha_seek(stream, word, s_size, fold)
16: FILE *stream;
17: char *word;
18: long int s_size;
19: int fold;
20: {
21: long int high, low, mid; /* point to beginning of a line in stream */
22: int ans; /* line(low) < word <= line(high) */
23: char line[maxstr];
24:
25:
26: /* initialize low (return if first line >= word) */
27: low= 0L;
28: pos(low);
29: getline(stream, line);
30: if (fold) foldline(line);
31: ans= strcmp(line,word);
32:
33: if ( ans >= 0)
34: {
35: pos(low);
36: return(ans==0);
37: }
38:
39: /* initialize high to "line" after last line */
40: high= s_size;
41:
42: mid= nextline(stream, nexttry );
43: while (mid < high )
44: {
45: getline(stream,line);
46: if (fold) foldline(line);
47: if (strcmp(line,word) < 0) low= mid;
48: else high= mid;
49: mid= nextline(stream, nexttry );
50: }
51:
52: /* linear search from low to high */
53: low= nextline(stream,low);
54: for(;;)
55: {
56: if (low>=high) break;
57:
58: getline(stream,line);
59: if (fold) foldline(line);
60: ans=strcmp(line,word);
61:
62: if (ans>=0) break;
63: low= ftell(stream);
64: }
65:
66: pos(low);
67: if (low==high) return(0);
68: else return(ans==0);
69: }
70:
71:
72: /* foldline(p): change all uppercase to lowercase in string p
73: */
74: foldline(p)
75: char *p;
76: {
77: for (; *p!=NULL; p++)
78: {
79: if (isupper(*p)) *p = tolower(*p);
80: }
81: }
This archive runs on limited infrastructure. Preserving old code on modern bandwidth. Automated agents are requested to crawl responsibly.