1 /* tac - concatenate and print files in reverse
2 Copyright (C) 1988, 1989, 1990, 1991 Free Software Foundation, Inc.
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2, or (at your option)
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */
18 /* Written by Jay Lepreau (lepreau@cs.utah.edu).
19 GNU enhancements by David MacKenzie (djm@gnu.ai.mit.edu). */
21 /* Copy each FILE, or the standard input if none are given or when a
22 FILE name of "-" is encountered, to the standard output with the
23 order of the records reversed. The records are separated by
24 instances of a string, or a newline if none is given. By default, the
25 separator string is attached to the end of the record that it
29 -b, --before The separator is attached to the beginning
30 of the record that it precedes in the file.
31 -r, --regex The separator is a regular expression.
32 -s, --separator=separator Use SEPARATOR as the record separator.
34 To reverse a file byte by byte, use (in bash, ksh, or sh):
40 #include <sys/types.h>
51 /* The number of bytes per atomic read. */
52 #define INITIAL_READSIZE 8192
54 /* The number of bytes per atomic write. */
55 #define WRITESIZE 8192
59 static RETSIGTYPE cleanup ();
61 static int tac_file ();
62 static int tac_stdin ();
63 static char *xmalloc ();
64 static char *xrealloc ();
65 static void output ();
66 static void save_stdin ();
67 static void xwrite ();
71 /* The name this program was run with. */
74 /* The string that separates the records of the file. */
75 static char *separator;
77 /* If nonzero, print `separator' along with the record preceding it
78 in the file; otherwise with the record following it. */
79 static int separator_ends_record;
81 /* 0 if `separator' is to be matched as a regular expression;
82 otherwise, the length of `separator', used as a sentinel to
84 static int sentinel_length;
86 /* The length of a match with `separator'. If `sentinel_length' is 0,
87 `match_length' is computed every time a match succeeds;
88 otherwise, it is simply the length of `separator'. */
89 static int match_length;
91 /* The input buffer. */
94 /* The number of bytes to read at once into `buffer'. */
95 static unsigned read_size;
97 /* The size of `buffer'. This is read_size * 2 + sentinel_length + 2.
98 The extra 2 bytes allow `past_end' to have a value beyond the
99 end of `buffer' and `match_start' to run off the front of `buffer'. */
100 static unsigned buffer_size;
102 /* The compiled regular expression representing `separator'. */
103 static struct re_pattern_buffer compiled_separator;
105 /* If non-zero, display usage information and exit. */
106 static int flag_help;
108 /* If non-zero, print the version on standard error. */
109 static int flag_version;
111 static struct option const longopts[] =
113 {"before", no_argument, &separator_ends_record, 0},
114 {"regex", no_argument, &sentinel_length, 0},
115 {"separator", required_argument, NULL, 's'},
116 {"help", no_argument, &flag_help, 1},
117 {"version", no_argument, &flag_version, 1},
125 Usage: %s [-br] [-s separator] [--before] [--regex] [--separator=separator]\n\
126 [--help] [--version] [file...]\n",
136 const char *error_message; /* Return value from re_compile_pattern. */
138 int have_read_stdin = 0;
140 program_name = argv[0];
144 separator_ends_record = 1;
146 while ((optc = getopt_long (argc, argv, "brs:", longopts, (int *) 0))
154 separator_ends_record = 0;
162 error (1, 0, "separator cannot be empty");
170 fprintf (stderr, "%s\n", version_string);
175 if (sentinel_length == 0)
177 compiled_separator.allocated = 100;
178 compiled_separator.buffer = (unsigned char *)
179 xmalloc (compiled_separator.allocated);
180 compiled_separator.fastmap = xmalloc (256);
181 compiled_separator.translate = 0;
182 error_message = re_compile_pattern (separator, strlen (separator),
183 &compiled_separator);
185 error (1, 0, "%s", error_message);
188 match_length = sentinel_length = strlen (separator);
190 read_size = INITIAL_READSIZE;
191 /* A precaution that will probably never be needed. */
192 while (sentinel_length * 2 >= read_size)
194 buffer_size = read_size * 2 + sentinel_length + 2;
195 buffer = xmalloc (buffer_size);
198 strcpy (buffer, separator);
199 buffer += sentinel_length;
207 errors = tac_stdin ();
210 for (; optind < argc; ++optind)
212 if (strcmp (argv[optind], "-") == 0)
215 errors |= tac_stdin ();
218 errors |= tac_file (argv[optind]);
221 /* Flush the output buffer. */
222 output ((char *) NULL, (char *) NULL);
224 if (have_read_stdin && close (0) < 0)
225 error (1, errno, "-");
227 error (1, errno, "write error");
231 /* The name of a temporary file containing a copy of pipe input. */
234 /* Print the standard input in reverse, saving it to temporary
235 file `tempfile' first if it is a pipe.
236 Return 0 if ok, 1 if an error occurs. */
241 /* Previous values of signal handlers. */
242 RETSIGTYPE (*sigint) (), (*sighup) (), (*sigpipe) (), (*sigterm) ();
245 #ifdef _POSIX_VERSION
246 struct sigaction oldact, newact;
247 #endif /* _POSIX_VERSION */
249 /* No tempfile is needed for "tac < file".
250 Use fstat instead of checking for errno == ESPIPE because
251 lseek doesn't work on some special files but doesn't return an
253 if (fstat (0, &stats))
255 error (0, errno, "standard input");
258 if (S_ISREG (stats.st_mode))
259 return tac (0, "standard input");
261 #ifdef _POSIX_VERSION
262 newact.sa_handler = cleanup;
263 sigemptyset (&newact.sa_mask);
266 sigaction (SIGINT, NULL, &oldact);
267 sigint = oldact.sa_handler;
268 if (sigint != SIG_IGN)
269 sigaction (SIGINT, &newact, NULL);
271 sigaction (SIGHUP, NULL, &oldact);
272 sighup = oldact.sa_handler;
273 if (sighup != SIG_IGN)
274 sigaction (SIGHUP, &newact, NULL);
276 sigaction (SIGPIPE, NULL, &oldact);
277 sigpipe = oldact.sa_handler;
278 if (sigpipe != SIG_IGN)
279 sigaction (SIGPIPE, &newact, NULL);
281 sigaction (SIGTERM, NULL, &oldact);
282 sigterm = oldact.sa_handler;
283 if (sigterm != SIG_IGN)
284 sigaction (SIGTERM, &newact, NULL);
285 #else /* !_POSIX_VERSION */
286 sigint = signal (SIGINT, SIG_IGN);
287 if (sigint != SIG_IGN)
288 signal (SIGINT, cleanup);
290 sighup = signal (SIGHUP, SIG_IGN);
291 if (sighup != SIG_IGN)
292 signal (SIGHUP, cleanup);
294 sigpipe = signal (SIGPIPE, SIG_IGN);
295 if (sigpipe != SIG_IGN)
296 signal (SIGPIPE, cleanup);
298 sigterm = signal (SIGTERM, SIG_IGN);
299 if (sigterm != SIG_IGN)
300 signal (SIGTERM, cleanup);
301 #endif /* _POSIX_VERSION */
305 errors = tac_file (tempfile);
309 #ifdef _POSIX_VERSION
310 newact.sa_handler = sigint;
311 sigaction (SIGINT, &newact, NULL);
312 newact.sa_handler = sighup;
313 sigaction (SIGHUP, &newact, NULL);
314 newact.sa_handler = sigterm;
315 sigaction (SIGTERM, &newact, NULL);
316 newact.sa_handler = sigpipe;
317 sigaction (SIGPIPE, &newact, NULL);
318 #else /* !_POSIX_VERSION */
319 signal (SIGINT, sigint);
320 signal (SIGHUP, sighup);
321 signal (SIGTERM, sigterm);
322 signal (SIGPIPE, sigpipe);
323 #endif /* _POSIX_VERSION */
328 /* Make a copy of the standard input in `tempfile'. */
333 static char *template = NULL;
334 static char *tempdir;
338 if (template == NULL)
340 tempdir = getenv ("TMPDIR");
343 template = xmalloc (strlen (tempdir) + 11);
345 sprintf (template, "%s/tacXXXXXX", tempdir);
346 tempfile = mktemp (template);
348 fd = creat (tempfile, 0600);
351 error (0, errno, "%s", tempfile);
354 while ((bytes_read = read (0, buffer, read_size)) > 0)
355 if (write (fd, buffer, bytes_read) != bytes_read)
357 error (0, errno, "%s", tempfile);
362 error (0, errno, "%s", tempfile);
365 if (bytes_read == -1)
367 error (0, errno, "read error");
372 /* Print FILE in reverse.
373 Return 0 if ok, 1 if an error occurs. */
384 error (0, errno, "%s", file);
387 errors = tac (fd, file);
390 error (0, errno, "%s", file);
396 /* Print in reverse the file open on descriptor FD for reading FILE.
397 Return 0 if ok, 1 if an error occurs. */
404 /* Pointer to the location in `buffer' where the search for
405 the next separator will begin. */
407 /* Pointer to one past the rightmost character in `buffer' that
408 has not been printed yet. */
410 unsigned saved_record_size; /* Length of the record growing in `buffer'. */
411 off_t file_pos; /* Offset in the file of the next read. */
412 /* Nonzero if `output' has not been called yet for any file.
413 Only used when the separator is attached to the preceding record. */
415 char first_char = *separator; /* Speed optimization, non-regexp. */
416 char *separator1 = separator + 1; /* Speed optimization, non-regexp. */
417 int match_length1 = match_length - 1; /* Speed optimization, non-regexp. */
418 struct re_registers regs;
420 /* Find the size of the input file. */
421 file_pos = lseek (fd, (off_t) 0, SEEK_END);
423 return 0; /* It's an empty file. */
425 /* Arrange for the first read to lop off enough to leave the rest of the
426 file a multiple of `read_size'. Since `read_size' can change, this may
427 not always hold during the program run, but since it usually will, leave
428 it here for i/o efficiency (page/sector boundaries and all that).
429 Note: the efficiency gain has not been verified. */
430 saved_record_size = file_pos % read_size;
431 if (saved_record_size == 0)
432 saved_record_size = read_size;
433 file_pos -= saved_record_size;
434 /* `file_pos' now points to the start of the last (probably partial) block
435 in the input file. */
437 lseek (fd, file_pos, SEEK_SET);
438 if (read (fd, buffer, saved_record_size) != saved_record_size)
440 error (0, 1, "%s", file);
444 match_start = past_end = buffer + saved_record_size;
445 /* For non-regexp search, move past impossible positions for a match. */
447 match_start -= match_length1;
451 /* Search backward from `match_start' - 1 to `buffer' for a match
452 with `separator'; for speed, use strncmp if `separator' contains no
454 If the match succeeds, set `match_start' to point to the start of
455 the match and `match_length' to the length of the match.
456 Otherwise, make `match_start' < `buffer'. */
457 if (sentinel_length == 0)
459 int i = match_start - buffer;
462 ret = re_search (&compiled_separator, buffer, i, i - 1, -i, ®s);
464 match_start = buffer - 1;
467 error (0, 0, "error in regular expression search");
472 match_start = buffer + regs.start[0];
473 match_length = regs.end[0] - regs.start[0];
478 /* `match_length' is constant for non-regexp boundaries. */
479 while (*--match_start != first_char
480 || (match_length1 && strncmp (match_start + 1, separator1,
485 /* Check whether we backed off the front of `buffer' without finding
486 a match for `separator'. */
487 if (match_start < buffer)
491 /* Hit the beginning of the file; print the remaining record. */
492 output (buffer, past_end);
496 saved_record_size = past_end - buffer;
497 if (saved_record_size > read_size)
499 /* `buffer_size' is about twice `read_size', so since
500 we want to read in another `read_size' bytes before
501 the data already in `buffer', we need to increase
504 int offset = sentinel_length ? sentinel_length : 1;
507 buffer_size = read_size * 2 + sentinel_length + 2;
508 newbuffer = xrealloc (buffer - offset, buffer_size) + offset;
509 /* Adjust the pointers for the new buffer location. */
510 match_start += newbuffer - buffer;
511 past_end += newbuffer - buffer;
515 /* Back up to the start of the next bufferfull of the file. */
516 if (file_pos >= read_size)
517 file_pos -= read_size;
520 read_size = file_pos;
523 lseek (fd, file_pos, SEEK_SET);
525 /* Shift the pending record data right to make room for the new. */
526 bcopy (buffer, buffer + read_size, saved_record_size);
527 past_end = buffer + read_size + saved_record_size;
528 /* For non-regexp searches, avoid unneccessary scanning. */
530 match_start = buffer + read_size;
532 match_start = past_end;
534 if (read (fd, buffer, read_size) != read_size)
536 error (0, errno, "%s", file);
542 /* Found a match of `separator'. */
543 if (separator_ends_record)
545 char *match_end = match_start + match_length;
547 /* If this match of `separator' isn't at the end of the
548 file, print the record. */
549 if (first_time == 0 || match_end != past_end)
550 output (match_end, past_end);
551 past_end = match_end;
556 output (match_start, past_end);
557 past_end = match_start;
559 match_start -= match_length - 1;
564 /* Print the characters from START to PAST_END - 1.
565 If START is NULL, just flush the buffer. */
568 output (start, past_end)
572 static char buffer[WRITESIZE];
573 static int bytes_in_buffer = 0;
574 int bytes_to_add = past_end - start;
575 int bytes_available = WRITESIZE - bytes_in_buffer;
579 xwrite (1, buffer, bytes_in_buffer);
584 /* Write out as many full buffers as possible. */
585 while (bytes_to_add >= bytes_available)
587 bcopy (start, buffer + bytes_in_buffer, bytes_available);
588 bytes_to_add -= bytes_available;
589 start += bytes_available;
590 xwrite (1, buffer, WRITESIZE);
592 bytes_available = WRITESIZE;
595 bcopy (start, buffer + bytes_in_buffer, bytes_to_add);
596 bytes_in_buffer += bytes_to_add;
607 xwrite (desc, buffer, size)
612 if (write (desc, buffer, size) != size)
614 error (0, errno, "write error");
619 /* Allocate N bytes of memory dynamically, with error checking. */
630 error (0, 0, "virtual memory exhausted");
636 /* Change the size of memory area P to N bytes, with error checking. */
646 error (0, 0, "virtual memory exhausted");