1 /* tail -- output the last part of file(s)
2 Copyright (C) 89, 90, 91, 95, 1996 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
18 /* Can display any amount of data, unlike the Unix version, which uses
19 a fixed size buffer and therefore can only deliver a limited number
23 -b Tail by N 512-byte blocks.
24 -c, --bytes=N[bkm] Tail by N bytes
25 [or 512-byte blocks, kilobytes, or megabytes].
26 -f, --follow Loop forever trying to read more characters at the
27 end of the file, on the assumption that the file
28 is growing. Ignored if reading from a pipe.
29 -n, --lines=N Tail by N lines.
30 -q, --quiet, --silent Never print filename headers.
31 -v, --verbose Always print filename headers.
33 If a number (N) starts with a `+', begin printing with the Nth item
34 from the start of each file, instead of from the end.
36 Reads from standard input if no files are given or when a filename of
38 By default, filename headers are printed only more than one file
40 By default, prints the last 10 lines (tail -n 10).
42 Original version by Paul Rubin <phr@ocf.berkeley.edu>.
43 Extensions by David MacKenzie <djm@gnu.ai.mit.edu>.
44 tail -f for multiple files by Ian Lance Taylor <ian@airs.com>. */
51 #include <sys/types.h>
54 /* Disable assertions. Some systems have broken assert macros. */
58 static void error(int i, int errnum, char* fmt, const char *msg)
60 fprintf(stderr, fmt, msg);
66 #define XWRITE(fd, buffer, n_bytes) \
70 assert ((n_bytes) >= 0); \
71 if (n_bytes > 0 && fwrite ((buffer), 1, (n_bytes), stdout) == 0) \
72 error (EXIT_FAILURE, errno, "write error", NULL); \
76 /* Number of items to tail. */
77 #define DEFAULT_N_LINES 10
79 /* Size of atomic reads. */
81 #define BUFSIZ (512 * 8)
84 /* If nonzero, interpret the numeric argument as the number of lines.
85 Otherwise, interpret it as the number of bytes. */
86 static int count_lines;
88 /* If nonzero, read from the end of one file until killed. */
91 /* If nonzero, read from the end of multiple files until killed. */
92 static int forever_multiple;
94 /* Array of file descriptors if forever_multiple is 1. */
95 static int *file_descs;
97 /* Array of file sizes if forever_multiple is 1. */
98 static off_t *file_sizes;
100 /* If nonzero, count from start of file instead of end. */
101 static int from_start;
103 /* If nonzero, print filename headers. */
104 static int print_headers;
106 /* When to print the filename banners. */
109 multiple_files, always, never
115 /* The name this program was run with. */
118 /* Nonzero if we have ever read standard input. */
119 static int have_read_stdin;
121 /* If nonzero, display usage information and exit. */
122 static int show_help;
124 /* If nonzero, print the version on standard output then exit. */
125 static int show_version;
127 static const char tail_usage[] =
128 "tail [OPTION]... [FILE]...\n\
129 Print last 10 lines of each FILE to standard output.\n\
130 With more than one FILE, precede each with a header giving the file name.\n\
131 With no FILE, or when FILE is -, read standard input.\n\
133 -c, --bytes=N output the last N bytes\n\
134 -f, --follow output appended data as the file grows\n\
135 -n, --lines=N output the last N lines, instead of last 10\n\
136 -q, --quiet, --silent never output headers giving file names\n\
137 -v, --verbose always output headers giving file names\n\
138 --help display this help and exit\n\
139 --version output version information and exit\n\
141 If the first character of N (the number of bytes or lines) is a `+',\n\
142 print beginning with the Nth item from the start of each file, otherwise,\n\
143 print the last N items in the file. N may have a multiplier suffix:\n\
144 b for 512, k for 1024, m for 1048576 (1 Meg). A first OPTION of -VALUE\n\
145 or +VALUE is treated like -n VALUE or -n +VALUE unless VALUE has one of\n\
146 the [bkm] suffix multipliers, in which case it is treated like -c VALUE\n\
150 write_header (const char *filename, const char *comment)
152 static int first_file = 1;
154 printf ("%s==> %s%s%s <==\n", (first_file ? "" : "\n"), filename,
155 (comment ? ": " : ""),
156 (comment ? comment : ""));
160 /* Print the last N_LINES lines from the end of file FD.
161 Go backward through the file, reading `BUFSIZ' bytes at a time (except
162 probably the first), until we hit the start of the file or have
163 read NUMBER newlines.
164 POS starts out as the length of the file (the offset of the last
165 byte of the file + 1).
166 Return 0 if successful, 1 if an error occurred. */
169 file_lines (const char *filename, int fd, long int n_lines, off_t pos)
173 int i; /* Index into `buffer' for scanning. */
178 /* Set `bytes_read' to the size of the last, probably partial, buffer;
179 0 < `bytes_read' <= `BUFSIZ'. */
180 bytes_read = pos % BUFSIZ;
183 /* Make `pos' a multiple of `BUFSIZ' (0 if the file is short), so that all
184 reads will be on block boundaries, which might increase efficiency. */
186 lseek (fd, pos, SEEK_SET);
187 bytes_read = safe_read (fd, buffer, bytes_read);
188 if (bytes_read == -1)
190 error (0, errno, "%s", filename);
194 /* Count the incomplete line on files that don't end with a newline. */
195 if (bytes_read && buffer[bytes_read - 1] != '\n')
200 /* Scan backward, counting the newlines in this bufferfull. */
201 for (i = bytes_read - 1; i >= 0; i--)
203 /* Have we counted the requested number of newlines yet? */
204 if (buffer[i] == '\n' && n_lines-- == 0)
206 /* If this newline wasn't the last character in the buffer,
207 print the text after it. */
208 if (i != bytes_read - 1)
209 XWRITE (STDOUT_FILENO, &buffer[i + 1], bytes_read - (i + 1));
213 /* Not enough newlines in that bufferfull. */
216 /* Not enough lines in the file; print the entire file. */
217 lseek (fd, (off_t) 0, SEEK_SET);
221 lseek (fd, pos, SEEK_SET);
223 while ((bytes_read = safe_read (fd, buffer, BUFSIZ)) > 0);
224 if (bytes_read == -1)
226 error (0, errno, "%s", filename);
232 /* Print the last N_LINES lines from the end of the standard input,
233 open for reading as pipe FD.
234 Buffer the text as a linked list of LBUFFERs, adding them as needed.
235 Return 0 if successful, 1 if an error occured. */
238 pipe_lines (const char *filename, int fd, long int n_lines)
244 struct linebuffer *next;
246 typedef struct linebuffer LBUFFER;
247 LBUFFER *first, *last, *tmp;
248 int i; /* Index into buffers. */
249 int total_lines = 0; /* Total number of newlines in all buffers. */
252 first = last = (LBUFFER *) xmalloc (sizeof (LBUFFER));
253 first->nbytes = first->nlines = 0;
255 tmp = (LBUFFER *) xmalloc (sizeof (LBUFFER));
257 /* Input is always read into a fresh buffer. */
258 while ((tmp->nbytes = safe_read (fd, tmp->buffer, BUFSIZ)) > 0)
263 /* Count the number of newlines just read. */
264 for (i = 0; i < tmp->nbytes; i++)
265 if (tmp->buffer[i] == '\n')
267 total_lines += tmp->nlines;
269 /* If there is enough room in the last buffer read, just append the new
270 one to it. This is because when reading from a pipe, `nbytes' can
271 often be very small. */
272 if (tmp->nbytes + last->nbytes < BUFSIZ)
274 memcpy (&last->buffer[last->nbytes], tmp->buffer, tmp->nbytes);
275 last->nbytes += tmp->nbytes;
276 last->nlines += tmp->nlines;
280 /* If there's not enough room, link the new buffer onto the end of
281 the list, then either free up the oldest buffer for the next
282 read if that would leave enough lines, or else malloc a new one.
283 Some compaction mechanism is possible but probably not
285 last = last->next = tmp;
286 if (total_lines - first->nlines > n_lines)
289 total_lines -= first->nlines;
293 tmp = (LBUFFER *) xmalloc (sizeof (LBUFFER));
296 if (tmp->nbytes == -1)
298 error (0, errno, "%s", filename);
306 /* This prevents a core dump when the pipe contains no newlines. */
310 /* Count the incomplete line on files that don't end with a newline. */
311 if (last->buffer[last->nbytes - 1] != '\n')
317 /* Run through the list, printing lines. First, skip over unneeded
319 for (tmp = first; total_lines - tmp->nlines > n_lines; tmp = tmp->next)
320 total_lines -= tmp->nlines;
322 /* Find the correct beginning, then print the rest of the file. */
323 if (total_lines > n_lines)
327 /* Skip `total_lines' - `n_lines' newlines. We made sure that
328 `total_lines' - `n_lines' <= `tmp->nlines'. */
330 for (i = total_lines - n_lines; i; --i)
331 while (*cp++ != '\n')
333 i = cp - tmp->buffer;
337 XWRITE (STDOUT_FILENO, &tmp->buffer[i], tmp->nbytes - i);
339 for (tmp = tmp->next; tmp; tmp = tmp->next)
340 XWRITE (STDOUT_FILENO, tmp->buffer, tmp->nbytes);
346 free ((char *) first);
352 /* Print the last N_BYTES characters from the end of pipe FD.
353 This is a stripped down version of pipe_lines.
354 Return 0 if successful, 1 if an error occurred. */
357 pipe_bytes (const char *filename, int fd, off_t n_bytes)
363 struct charbuffer *next;
365 typedef struct charbuffer CBUFFER;
366 CBUFFER *first, *last, *tmp;
367 int i; /* Index into buffers. */
368 int total_bytes = 0; /* Total characters in all buffers. */
371 first = last = (CBUFFER *) xmalloc (sizeof (CBUFFER));
374 tmp = (CBUFFER *) xmalloc (sizeof (CBUFFER));
376 /* Input is always read into a fresh buffer. */
377 while ((tmp->nbytes = safe_read (fd, tmp->buffer, BUFSIZ)) > 0)
381 total_bytes += tmp->nbytes;
382 /* If there is enough room in the last buffer read, just append the new
383 one to it. This is because when reading from a pipe, `nbytes' can
384 often be very small. */
385 if (tmp->nbytes + last->nbytes < BUFSIZ)
387 memcpy (&last->buffer[last->nbytes], tmp->buffer, tmp->nbytes);
388 last->nbytes += tmp->nbytes;
392 /* If there's not enough room, link the new buffer onto the end of
393 the list, then either free up the oldest buffer for the next
394 read if that would leave enough characters, or else malloc a new
395 one. Some compaction mechanism is possible but probably not
397 last = last->next = tmp;
398 if (total_bytes - first->nbytes > n_bytes)
401 total_bytes -= first->nbytes;
406 tmp = (CBUFFER *) xmalloc (sizeof (CBUFFER));
410 if (tmp->nbytes == -1)
412 error (0, errno, "%s", filename);
420 /* Run through the list, printing characters. First, skip over unneeded
422 for (tmp = first; total_bytes - tmp->nbytes > n_bytes; tmp = tmp->next)
423 total_bytes -= tmp->nbytes;
425 /* Find the correct beginning, then print the rest of the file.
426 We made sure that `total_bytes' - `n_bytes' <= `tmp->nbytes'. */
427 if (total_bytes > n_bytes)
428 i = total_bytes - n_bytes;
431 XWRITE (STDOUT_FILENO, &tmp->buffer[i], tmp->nbytes - i);
433 for (tmp = tmp->next; tmp; tmp = tmp->next)
434 XWRITE (STDOUT_FILENO, tmp->buffer, tmp->nbytes);
440 free ((char *) first);
446 /* Skip N_BYTES characters from the start of pipe FD, and print
447 any extra characters that were read beyond that.
448 Return 1 on error, 0 if ok. */
451 start_bytes (const char *filename, int fd, off_t n_bytes)
456 while (n_bytes > 0 && (bytes_read = safe_read (fd, buffer, BUFSIZ)) > 0)
457 n_bytes -= bytes_read;
458 if (bytes_read == -1)
460 error (0, errno, "%s", filename);
463 else if (n_bytes < 0)
464 XWRITE (STDOUT_FILENO, &buffer[bytes_read + n_bytes], -n_bytes);
468 /* Skip N_LINES lines at the start of file or pipe FD, and print
469 any extra characters that were read beyond that.
470 Return 1 on error, 0 if ok. */
473 start_lines (const char *filename, int fd, long int n_lines)
477 int bytes_to_skip = 0;
479 while (n_lines && (bytes_read = safe_read (fd, buffer, BUFSIZ)) > 0)
482 while (bytes_to_skip < bytes_read)
483 if (buffer[bytes_to_skip++] == '\n' && --n_lines == 0)
486 if (bytes_read == -1)
488 error (0, errno, "%s", filename);
491 else if (bytes_to_skip < bytes_read)
493 XWRITE (STDOUT_FILENO, &buffer[bytes_to_skip],
494 bytes_read - bytes_to_skip);
499 /* Display file FILENAME from the current position in FD to the end.
500 If `forever' is nonzero, keep reading from the end of the file
501 until killed. Return the number of bytes read from the file. */
504 dump_remainder (const char *filename, int fd)
512 while ((bytes_read = safe_read (fd, buffer, BUFSIZ)) > 0)
514 XWRITE (STDOUT_FILENO, buffer, bytes_read);
517 if (bytes_read == -1)
518 error (EXIT_FAILURE, errno, "%s", filename);
527 if (forever_multiple)
534 /* Tail NFILES (>1) files forever until killed. The file names are in
535 NAMES. The open file descriptors are in `file_descs', and the size
536 at which we stopped tailing them is in `file_sizes'. We loop over
537 each of them, doing an fstat to see if they have changed size. If
538 none of them have changed size in one iteration, we sleep for a
539 second and try again. We do this until the user interrupts us. */
542 tail_forever (char **names, int nfiles)
554 for (i = 0; i < nfiles; i++)
558 if (file_descs[i] < 0)
560 if (fstat (file_descs[i], &stats) < 0)
562 error (0, errno, "%s", names[i]);
566 if (stats.st_size == file_sizes[i])
569 /* This file has changed size. Print out what we can, and
570 then keep looping. */
574 if (stats.st_size < file_sizes[i])
576 write_header (names[i], "file truncated");
578 lseek (file_descs[i], stats.st_size, SEEK_SET);
579 file_sizes[i] = stats.st_size;
586 write_header (names[i], NULL);
589 file_sizes[i] += dump_remainder (names[i], file_descs[i]);
592 /* If none of the files changed size, sleep. */
598 /* Output the last N_BYTES bytes of file FILENAME open for reading in FD.
599 Return 0 if successful, 1 if an error occurred. */
602 tail_bytes (const char *filename, int fd, off_t n_bytes)
606 /* FIXME: resolve this like in dd.c. */
607 /* Use fstat instead of checking for errno == ESPIPE because
608 lseek doesn't work on some special files but doesn't return an
610 if (fstat (fd, &stats))
612 error (0, errno, "%s", filename);
618 if (S_ISREG (stats.st_mode))
619 lseek (fd, n_bytes, SEEK_CUR);
620 else if (start_bytes (filename, fd, n_bytes))
622 dump_remainder (filename, fd);
626 if (S_ISREG (stats.st_mode))
628 off_t current_pos, end_pos;
629 size_t bytes_remaining;
631 if ((current_pos = lseek (fd, (off_t) 0, SEEK_CUR)) != -1
632 && (end_pos = lseek (fd, (off_t) 0, SEEK_END)) != -1)
635 /* Be careful here. The current position may actually be
636 beyond the end of the file. */
637 bytes_remaining = (diff = end_pos - current_pos) < 0 ? 0 : diff;
641 error (0, errno, "%s", filename);
645 if (bytes_remaining <= n_bytes)
647 /* From the current position to end of file, there are no
648 more bytes than have been requested. So reposition the
649 file pointer to the incoming current position and print
650 everything after that. */
651 lseek (fd, current_pos, SEEK_SET);
655 /* There are more bytes remaining than were requested.
657 lseek (fd, -n_bytes, SEEK_END);
659 dump_remainder (filename, fd);
662 return pipe_bytes (filename, fd, n_bytes);
667 /* Output the last N_LINES lines of file FILENAME open for reading in FD.
668 Return 0 if successful, 1 if an error occurred. */
671 tail_lines (const char *filename, int fd, long int n_lines)
676 if (fstat (fd, &stats))
678 error (0, errno, "%s", filename);
684 if (start_lines (filename, fd, n_lines))
686 dump_remainder (filename, fd);
690 /* Use file_lines only if FD refers to a regular file with
691 its file pointer positioned at beginning of file. */
692 /* FIXME: adding the lseek conjunct is a kludge.
693 Once there's a reasonable test suite, fix the true culprit:
694 file_lines. file_lines shouldn't presume that the input
695 file pointer is initially positioned to beginning of file. */
696 if (S_ISREG (stats.st_mode)
697 && lseek (fd, (off_t) 0, SEEK_CUR) == (off_t) 0)
699 length = lseek (fd, (off_t) 0, SEEK_END);
700 if (length != 0 && file_lines (filename, fd, n_lines, length))
702 dump_remainder (filename, fd);
705 return pipe_lines (filename, fd, n_lines);
710 /* Display the last N_UNITS units of file FILENAME, open for reading
712 Return 0 if successful, 1 if an error occurred. */
715 tail (const char *filename, int fd, off_t n_units)
718 return tail_lines (filename, fd, (long) n_units);
720 return tail_bytes (filename, fd, n_units);
723 /* Display the last N_UNITS units of file FILENAME.
724 "-" for FILENAME means the standard input.
725 FILENUM is this file's index in the list of files the user gave.
726 Return 0 if successful, 1 if an error occurred. */
729 tail_file (const char *filename, off_t n_units, int filenum)
734 if (!strcmp (filename, "-")
737 filename = "standard input";
739 write_header (filename, NULL);
740 errors = tail (filename, 0, n_units);
741 if (forever_multiple)
743 if (fstat (0, &stats) < 0)
745 error (0, errno, "standard input");
748 else if (!S_ISREG (stats.st_mode))
751 "standard input: cannot follow end of non-regular file");
755 file_descs[filenum] = -1;
758 file_descs[filenum] = 0;
759 file_sizes[filenum] = stats.st_size;
765 /* Not standard input. */
766 fd = open (filename, O_RDONLY);
769 if (forever_multiple)
770 file_descs[filenum] = -1;
771 error (0, errno, "%s", filename);
777 write_header (filename, NULL);
778 errors = tail (filename, fd, n_units);
779 if (forever_multiple)
781 if (fstat (fd, &stats) < 0)
783 error (0, errno, "%s", filename);
786 else if (!S_ISREG (stats.st_mode))
788 error (0, 0, "%s: cannot follow end of non-regular file",
795 file_descs[filenum] = -1;
799 file_descs[filenum] = fd;
800 file_sizes[filenum] = stats.st_size;
807 error (0, errno, "%s", filename);
818 tai_main (int argc, char **argv)
820 enum header_mode header_mode = multiple_files;
822 /* If from_start, the number of items to skip before printing; otherwise,
823 the number of items at the end of the file to print. Initially, -1
824 means the value has not been set. */
827 int c; /* Option character. */
831 program_name = argv[0];
834 forever = forever_multiple = from_start = print_headers = 0;
837 && ((argv[1][0] == '-' && ISDIGIT (argv[1][1]))
838 || (argv[1][0] == '+' && (ISDIGIT (argv[1][1])
839 || argv[1][1] == 0))))
841 /* Old option syntax: a dash or plus, one or more digits (zero digits
842 are acceptable with a plus), and one or more option letters. */
843 if (argv[1][0] == '+')
845 if (argv[1][1] != '\0')
850 s_err = xstrtol (++argv[1], &p, 0, &tmp_long, "bkm");
852 if (s_err == LONGINT_OVERFLOW)
854 STRTOL_FATAL_ERROR (argv[1], "argument", s_err);
857 /* If a [bkm] suffix was given then count bytes, not lines. */
858 if (p[-1] == 'b' || p[-1] == 'k' || p[-1] == 'm')
861 /* Parse any appended option letters. */
867 /* Interpret N_UNITS as # of bytes. */
884 header_mode = always;
888 error (0, 0, "unrecognized option '%c'", *p);
894 /* Make the options we just parsed invisible to getopt. */
902 printf ("tail - %s\n", PACKAGE_VERSION);
910 n_units = DEFAULT_N_LINES;
912 /* To start printing with item N_UNITS from the start of the file, skip
913 N_UNITS - 1 items. `tail +0' is actually meaningless, but for Unix
914 compatibility it's treated the same as `tail +1'. */
921 n_files = argc - optind;
922 file = argv + optind;
924 if (n_files > 1 && forever)
926 forever_multiple = 1;
928 file_descs = (int *) xmalloc (n_files * sizeof (int));
929 file_sizes = (off_t *) xmalloc (n_files * sizeof (off_t));
932 if (header_mode == always
933 || (header_mode == multiple_files && n_files > 1))
938 exit_status |= tail_file ("-", n_units, 0);
943 for (i = 0; i < n_files; i++)
944 exit_status |= tail_file (file[i], n_units, i);
946 if (forever_multiple)
947 tail_forever (file, n_files);
950 if (have_read_stdin && close (0) < 0)
951 error (EXIT_FAILURE, errno, "-");
952 if (fclose (stdout) == EOF)
953 error (EXIT_FAILURE, errno, "write error");
954 exit (exit_status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);