]> git.ipfire.org Git - thirdparty/util-linux.git/blob - misc-utils/look.c
libfdisk: (docs) add missing 'since' tags
[thirdparty/util-linux.git] / misc-utils / look.c
1 /*-
2 * Copyright (c) 1991, 1993
3 * The Regents of the University of California. All rights reserved.
4 *
5 * This code is derived from software contributed to Berkeley by
6 * David Hitz of Auspex Systems, Inc.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. All advertising materials mentioning features or use of this software
17 * must display the following acknowledgement:
18 * This product includes software developed by the University of
19 * California, Berkeley and its contributors.
20 * 4. Neither the name of the University nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
23 *
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * SUCH DAMAGE.
35 */
36
37 /* 1999-02-22 Arkadiusz Miƛkiewicz <misiek@pld.ORG.PL>
38 * - added Native Language Support
39 */
40
41 /*
42 * look -- find lines in a sorted list.
43 *
44 * The man page said that TABs and SPACEs participate in -d comparisons.
45 * In fact, they were ignored. This implements historic practice, not
46 * the manual page.
47 */
48
49 #include <sys/mman.h>
50 #include <sys/stat.h>
51 #include <errno.h>
52 #include <fcntl.h>
53 #include <stdio.h>
54 #include <stdlib.h>
55 #include <stddef.h>
56 #include <string.h>
57 #include <ctype.h>
58 #include <getopt.h>
59
60 #include "nls.h"
61 #include "xalloc.h"
62 #include "pathnames.h"
63 #include "closestream.h"
64
65 #define EQUAL 0
66 #define GREATER 1
67 #define LESS (-1)
68
69 static int dflag, fflag;
70 /* uglified the source a bit with globals, so that we only need
71 to allocate comparbuf once */
72 static int stringlen;
73 static char *string;
74 static char *comparbuf;
75
76 static char *binary_search (char *, char *);
77 static int compare (char *, char *);
78 static char *linear_search (char *, char *);
79 static int look (char *, char *);
80 static void print_from (char *, char *);
81 static void __attribute__ ((__noreturn__)) usage(FILE * out);
82
83 int
84 main(int argc, char *argv[])
85 {
86 struct stat sb;
87 int ch, fd, termchar;
88 char *back, *file, *front, *p;
89
90 static const struct option longopts[] = {
91 {"alternative", no_argument, NULL, 'a'},
92 {"alphanum", no_argument, NULL, 'd'},
93 {"ignore-case", no_argument, NULL, 'f'},
94 {"terminate", required_argument, NULL, 't'},
95 {"version", no_argument, NULL, 'V'},
96 {"help", no_argument, NULL, 'h'},
97 {NULL, 0, NULL, 0}
98 };
99
100 setlocale(LC_ALL, "");
101 bindtextdomain(PACKAGE, LOCALEDIR);
102 textdomain(PACKAGE);
103 atexit(close_stdout);
104
105 setlocale(LC_ALL, "");
106
107 file = _PATH_WORDS;
108 termchar = '\0';
109 string = NULL; /* just for gcc */
110
111 while ((ch = getopt_long(argc, argv, "adft:Vh", longopts, NULL)) != -1)
112 switch(ch) {
113 case 'a':
114 file = _PATH_WORDS_ALT;
115 break;
116 case 'd':
117 dflag = 1;
118 break;
119 case 'f':
120 fflag = 1;
121 break;
122 case 't':
123 termchar = *optarg;
124 break;
125 case 'V':
126 printf(UTIL_LINUX_VERSION);
127 return EXIT_SUCCESS;
128 case 'h':
129 usage(stdout);
130 default:
131 errtryhelp(EXIT_FAILURE);
132 }
133 argc -= optind;
134 argv += optind;
135
136 switch (argc) {
137 case 2: /* Don't set -df for user. */
138 string = *argv++;
139 file = *argv;
140 break;
141 case 1: /* But set -df by default. */
142 dflag = fflag = 1;
143 string = *argv;
144 break;
145 default:
146 usage(stderr);
147 }
148
149 if (termchar != '\0' && (p = strchr(string, termchar)) != NULL)
150 *++p = '\0';
151
152 if ((fd = open(file, O_RDONLY, 0)) < 0 || fstat(fd, &sb))
153 err(EXIT_FAILURE, "%s", file);
154 front = mmap(NULL, (size_t) sb.st_size, PROT_READ,
155 MAP_SHARED, fd, (off_t) 0);
156 if
157 #ifdef MAP_FAILED
158 (front == MAP_FAILED)
159 #else
160 ((void *)(front) <= (void *)0)
161 #endif
162 err(EXIT_FAILURE, "%s", file);
163 back = front + sb.st_size;
164 return look(front, back);
165 }
166
167 static int
168 look(char *front, char *back)
169 {
170 int ch;
171 char *readp, *writep;
172
173 /* Reformat string to avoid doing it multiple times later. */
174 if (dflag) {
175 for (readp = writep = string; (ch = *readp++) != 0;) {
176 if (isalnum(ch) || isblank(ch))
177 *(writep++) = ch;
178 }
179 *writep = '\0';
180 stringlen = writep - string;
181 } else
182 stringlen = strlen(string);
183
184 comparbuf = xmalloc(stringlen+1);
185
186 front = binary_search(front, back);
187 front = linear_search(front, back);
188
189 if (front)
190 print_from(front, back);
191
192 free(comparbuf);
193
194 return (front ? 0 : 1);
195 }
196
197
198 /*
199 * Binary search for "string" in memory between "front" and "back".
200 *
201 * This routine is expected to return a pointer to the start of a line at
202 * *or before* the first word matching "string". Relaxing the constraint
203 * this way simplifies the algorithm.
204 *
205 * Invariants:
206 * front points to the beginning of a line at or before the first
207 * matching string.
208 *
209 * back points to the beginning of a line at or after the first
210 * matching line.
211 *
212 * Advancing the Invariants:
213 *
214 * p = first newline after halfway point from front to back.
215 *
216 * If the string at "p" is not greater than the string to match,
217 * p is the new front. Otherwise it is the new back.
218 *
219 * Termination:
220 *
221 * The definition of the routine allows it return at any point,
222 * since front is always at or before the line to print.
223 *
224 * In fact, it returns when the chosen "p" equals "back". This
225 * implies that there exists a string is least half as long as
226 * (back - front), which in turn implies that a linear search will
227 * be no more expensive than the cost of simply printing a string or two.
228 *
229 * Trying to continue with binary search at this point would be
230 * more trouble than it's worth.
231 */
232 #define SKIP_PAST_NEWLINE(p, back) \
233 while (p < back && *p++ != '\n')
234
235 static char *
236 binary_search(char *front, char *back)
237 {
238 char *p;
239
240 p = front + (back - front) / 2;
241 SKIP_PAST_NEWLINE(p, back);
242
243 /*
244 * If the file changes underneath us, make sure we don't
245 * infinitely loop.
246 */
247 while (p < back && back > front) {
248 if (compare(p, back) == GREATER)
249 front = p;
250 else
251 back = p;
252 p = front + (back - front) / 2;
253 SKIP_PAST_NEWLINE(p, back);
254 }
255 return (front);
256 }
257
258 /*
259 * Find the first line that starts with string, linearly searching from front
260 * to back.
261 *
262 * Return NULL for no such line.
263 *
264 * This routine assumes:
265 *
266 * o front points at the first character in a line.
267 * o front is before or at the first line to be printed.
268 */
269 static char *
270 linear_search(char *front, char *back)
271 {
272 while (front < back) {
273 switch (compare(front, back)) {
274 case EQUAL: /* Found it. */
275 return (front);
276 case LESS: /* No such string. */
277 return (NULL);
278 case GREATER: /* Keep going. */
279 break;
280 }
281 SKIP_PAST_NEWLINE(front, back);
282 }
283 return (NULL);
284 }
285
286 /*
287 * Print as many lines as match string, starting at front.
288 */
289 static void
290 print_from(char *front, char *back)
291 {
292 int eol;
293
294 while (front < back && compare(front, back) == EQUAL) {
295 if (compare(front, back) == EQUAL) {
296 eol = 0;
297 while (front < back && !eol) {
298 if (putchar(*front) == EOF)
299 err(EXIT_FAILURE, "stdout");
300 if (*front++ == '\n')
301 eol = 1;
302 }
303 } else
304 SKIP_PAST_NEWLINE(front, back);
305 }
306 }
307
308 /*
309 * Return LESS, GREATER, or EQUAL depending on how string compares with
310 * string2 (s1 ??? s2).
311 *
312 * o Matches up to len(s1) are EQUAL.
313 * o Matches up to len(s2) are GREATER.
314 *
315 * Compare understands about the -f and -d flags, and treats comparisons
316 * appropriately.
317 *
318 * The string "string" is null terminated. The string "s2" is '\n' terminated
319 * (or "s2end" terminated).
320 *
321 * We use strcasecmp etc, since it knows how to ignore case also
322 * in other locales.
323 */
324 static int
325 compare(char *s2, char *s2end) {
326 int i;
327 char *p;
328
329 /* copy, ignoring things that should be ignored */
330 p = comparbuf;
331 i = stringlen;
332 while(s2 < s2end && *s2 != '\n' && i) {
333 if (!dflag || isalnum(*s2) || isblank(*s2))
334 {
335 *p++ = *s2;
336 i--;
337 }
338 s2++;
339 }
340 *p = 0;
341
342 /* and compare */
343 if (fflag)
344 i = strncasecmp(comparbuf, string, stringlen);
345 else
346 i = strncmp(comparbuf, string, stringlen);
347
348 return ((i > 0) ? LESS : (i < 0) ? GREATER : EQUAL);
349 }
350
351 static void __attribute__ ((__noreturn__)) usage(FILE * out)
352 {
353 fputs(USAGE_HEADER, out);
354 fprintf(out, _(" %s [options] <string> [<file>...]\n"), program_invocation_short_name);
355
356 fputs(USAGE_SEPARATOR, out);
357 fputs(_("Display lines beginning with a specified string.\n"), out);
358
359 fputs(USAGE_OPTIONS, out);
360 fputs(_(" -a, --alternative use the alternative dictionary\n"), out);
361 fputs(_(" -d, --alphanum compare only blanks and alphanumeric characters\n"), out);
362 fputs(_(" -f, --ignore-case ignore case differences when comparing\n"), out);
363 fputs(_(" -t, --terminate <char> define the string-termination character\n"), out);
364
365 fputs(USAGE_SEPARATOR, out);
366 fputs(USAGE_HELP, out);
367 fputs(USAGE_VERSION, out);
368 fprintf(out, USAGE_MAN_TAIL("look(1)"));
369
370 exit(out == stderr ? EXIT_FAILURE : EXIT_SUCCESS);
371 }