]> git.ipfire.org Git - thirdparty/util-linux.git/blob - misc-utils/look.c
textual: use manual tail usage() macro
[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 int dflag, fflag;
70 /* uglified the source a bit with globals, so that we only need
71 to allocate comparbuf once */
72 int stringlen;
73 char *string;
74 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 case '?':
131 default:
132 usage(stderr);
133 }
134 argc -= optind;
135 argv += optind;
136
137 switch (argc) {
138 case 2: /* Don't set -df for user. */
139 string = *argv++;
140 file = *argv;
141 break;
142 case 1: /* But set -df by default. */
143 dflag = fflag = 1;
144 string = *argv;
145 break;
146 default:
147 usage(stderr);
148 }
149
150 if (termchar != '\0' && (p = strchr(string, termchar)) != NULL)
151 *++p = '\0';
152
153 if ((fd = open(file, O_RDONLY, 0)) < 0 || fstat(fd, &sb))
154 err(EXIT_FAILURE, "%s", file);
155 front = mmap(NULL, (size_t) sb.st_size, PROT_READ,
156 #ifdef MAP_FILE
157 MAP_FILE |
158 #endif
159 MAP_SHARED, fd, (off_t) 0);
160 if
161 #ifdef MAP_FAILED
162 (front == MAP_FAILED)
163 #else
164 ((void *)(front) <= (void *)0)
165 #endif
166 err(EXIT_FAILURE, "%s", file);
167
168 #if 0
169 /* workaround for mmap problem (rmiller@duskglow.com) */
170 if (front == (void *)0)
171 return 1;
172 #endif
173
174 back = front + sb.st_size;
175 return look(front, back);
176 }
177
178 int
179 look(char *front, char *back)
180 {
181 int ch;
182 char *readp, *writep;
183
184 /* Reformat string string to avoid doing it multiple times later. */
185 if (dflag) {
186 for (readp = writep = string; (ch = *readp++) != 0;) {
187 if (isalnum(ch))
188 *(writep++) = ch;
189 }
190 *writep = '\0';
191 stringlen = writep - string;
192 } else
193 stringlen = strlen(string);
194
195 comparbuf = xmalloc(stringlen+1);
196
197 front = binary_search(front, back);
198 front = linear_search(front, back);
199
200 if (front)
201 print_from(front, back);
202
203 free(comparbuf);
204
205 return (front ? 0 : 1);
206 }
207
208
209 /*
210 * Binary search for "string" in memory between "front" and "back".
211 *
212 * This routine is expected to return a pointer to the start of a line at
213 * *or before* the first word matching "string". Relaxing the constraint
214 * this way simplifies the algorithm.
215 *
216 * Invariants:
217 * front points to the beginning of a line at or before the first
218 * matching string.
219 *
220 * back points to the beginning of a line at or after the first
221 * matching line.
222 *
223 * Advancing the Invariants:
224 *
225 * p = first newline after halfway point from front to back.
226 *
227 * If the string at "p" is not greater than the string to match,
228 * p is the new front. Otherwise it is the new back.
229 *
230 * Termination:
231 *
232 * The definition of the routine allows it return at any point,
233 * since front is always at or before the line to print.
234 *
235 * In fact, it returns when the chosen "p" equals "back". This
236 * implies that there exists a string is least half as long as
237 * (back - front), which in turn implies that a linear search will
238 * be no more expensive than the cost of simply printing a string or two.
239 *
240 * Trying to continue with binary search at this point would be
241 * more trouble than it's worth.
242 */
243 #define SKIP_PAST_NEWLINE(p, back) \
244 while (p < back && *p++ != '\n')
245
246 char *
247 binary_search(char *front, char *back)
248 {
249 char *p;
250
251 p = front + (back - front) / 2;
252 SKIP_PAST_NEWLINE(p, back);
253
254 /*
255 * If the file changes underneath us, make sure we don't
256 * infinitely loop.
257 */
258 while (p < back && back > front) {
259 if (compare(p, back) == GREATER)
260 front = p;
261 else
262 back = p;
263 p = front + (back - front) / 2;
264 SKIP_PAST_NEWLINE(p, back);
265 }
266 return (front);
267 }
268
269 /*
270 * Find the first line that starts with string, linearly searching from front
271 * to back.
272 *
273 * Return NULL for no such line.
274 *
275 * This routine assumes:
276 *
277 * o front points at the first character in a line.
278 * o front is before or at the first line to be printed.
279 */
280 char *
281 linear_search(char *front, char *back)
282 {
283 while (front < back) {
284 switch (compare(front, back)) {
285 case EQUAL: /* Found it. */
286 return (front);
287 break;
288 case LESS: /* No such string. */
289 return (NULL);
290 break;
291 case GREATER: /* Keep going. */
292 break;
293 }
294 SKIP_PAST_NEWLINE(front, back);
295 }
296 return (NULL);
297 }
298
299 /*
300 * Print as many lines as match string, starting at front.
301 */
302 void
303 print_from(char *front, char *back)
304 {
305 int eol;
306
307 while (front < back && compare(front, back) == EQUAL) {
308 if (compare(front, back) == EQUAL) {
309 eol = 0;
310 while (front < back && !eol) {
311 if (putchar(*front) == EOF)
312 err(EXIT_FAILURE, "stdout");
313 if (*front++ == '\n')
314 eol = 1;
315 }
316 } else
317 SKIP_PAST_NEWLINE(front, back);
318 }
319 }
320
321 /*
322 * Return LESS, GREATER, or EQUAL depending on how string compares with
323 * string2 (s1 ??? s2).
324 *
325 * o Matches up to len(s1) are EQUAL.
326 * o Matches up to len(s2) are GREATER.
327 *
328 * Compare understands about the -f and -d flags, and treats comparisons
329 * appropriately.
330 *
331 * The string "string" is null terminated. The string "s2" is '\n' terminated
332 * (or "s2end" terminated).
333 *
334 * We use strcasecmp etc, since it knows how to ignore case also
335 * in other locales.
336 */
337 int
338 compare(char *s2, char *s2end) {
339 int i;
340 char *p;
341
342 /* copy, ignoring things that should be ignored */
343 p = comparbuf;
344 i = stringlen;
345 while(s2 < s2end && *s2 != '\n' && i) {
346 if (!dflag || isalnum(*s2))
347 {
348 *p++ = *s2;
349 i--;
350 }
351 s2++;
352 }
353 *p = 0;
354
355 /* and compare */
356 if (fflag)
357 i = strncasecmp(comparbuf, string, stringlen);
358 else
359 i = strncmp(comparbuf, string, stringlen);
360
361 return ((i > 0) ? LESS : (i < 0) ? GREATER : EQUAL);
362 }
363
364 static void __attribute__ ((__noreturn__)) usage(FILE * out)
365 {
366 fputs(_("\nUsage:\n"), out),
367 fprintf(out,
368 _(" %s [options] string [file]\n"), program_invocation_short_name);
369
370 fputs(_("\nOptions:\n"), out);
371 fputs(_(" -a, --alternative use alternative dictionary\n"
372 " -d, --alphanum compare only alphanumeric characters\n"
373 " -f, --ignore-case ignore case differences when comparing\n"
374 " -t, --terminate <char> define string termination character\n"
375 " -V, --version output version information and exit\n"
376 " -h, --help display this help and exit\n\n"), out);
377
378 fprintf(out, USAGE_MAN_TAIL("look(1)"));
379 exit(out == stderr ? EXIT_FAILURE : EXIT_SUCCESS);
380 }