(add_tabstop): Give correct size when reallocating tab_list buffer.
[platform/upstream/coreutils.git] / src / tail.c
1 /* tail -- output the last part of file(s)
2    Copyright (C) 1989, 1990, 1991, 1995 Free Software Foundation, Inc.
3
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)
7    any later version.
8
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.
13
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.  */
17
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
20    of lines.
21
22    Options:
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.
32
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.
35
36    Reads from standard input if no files are given or when a filename of
37    ``-'' is encountered.
38    By default, filename headers are printed only more than one file
39    is given.
40    By default, prints the last 10 lines (tail -n 10).
41
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>.  */
45
46 #include <config.h>
47
48 #include <stdio.h>
49 #include <assert.h>
50 #include <getopt.h>
51 #include <sys/types.h>
52
53 #include "system.h"
54 #include "version.h"
55 #include "xstrtol.h"
56 #include "error.h"
57
58 /* Disable assertions.  Some systems have broken assert macros.  */
59 #define NDEBUG 1
60
61 #define XWRITE(fd, buffer, n_bytes)                                     \
62   do                                                                    \
63     {                                                                   \
64       assert ((fd) == 1);                                               \
65       assert ((n_bytes) >= 0);                                          \
66       if (n_bytes > 0 && fwrite ((buffer), 1, (n_bytes), stdout) == 0)  \
67         error (1, errno, "write error");                                \
68     }                                                                   \
69   while (0)
70
71 /* Number of items to tail.  */
72 #define DEFAULT_N_LINES 10
73
74 /* Size of atomic reads.  */
75 #ifndef BUFSIZ
76 #define BUFSIZ (512 * 8)
77 #endif
78
79 /* If nonzero, interpret the numeric argument as the number of lines.
80    Otherwise, interpret it as the number of bytes.  */
81 static int count_lines;
82
83 /* If nonzero, read from the end of one file until killed.  */
84 static int forever;
85
86 /* If nonzero, read from the end of multiple files until killed.  */
87 static int forever_multiple;
88
89 /* Array of file descriptors if forever_multiple is 1.  */
90 static int *file_descs;
91
92 /* Array of file sizes if forever_multiple is 1.  */
93 static off_t *file_sizes;
94
95 /* If nonzero, count from start of file instead of end.  */
96 static int from_start;
97
98 /* If nonzero, print filename headers.  */
99 static int print_headers;
100
101 /* When to print the filename banners.  */
102 enum header_mode
103 {
104   multiple_files, always, never
105 };
106
107 char *xmalloc ();
108 int safe_read ();
109
110 static int file_lines ();
111 static int pipe_bytes ();
112 static int pipe_lines ();
113 static int start_bytes ();
114 static int start_lines ();
115 static int tail ();
116 static int tail_bytes ();
117 static int tail_file ();
118 static int tail_lines ();
119 static long dump_remainder ();
120 static void tail_forever ();
121 static void usage ();
122 static void write_header ();
123
124 /* The name this program was run with.  */
125 char *program_name;
126
127 /* Nonzero if we have ever read standard input.  */
128 static int have_read_stdin;
129
130 /* If non-zero, display usage information and exit.  */
131 static int show_help;
132
133 /* If non-zero, print the version on standard output then exit.  */
134 static int show_version;
135
136 static struct option const long_options[] =
137 {
138   {"bytes", required_argument, NULL, 'c'},
139   {"follow", no_argument, NULL, 'f'},
140   {"lines", required_argument, NULL, 'n'},
141   {"quiet", no_argument, NULL, 'q'},
142   {"silent", no_argument, NULL, 'q'},
143   {"verbose", no_argument, NULL, 'v'},
144   {"help", no_argument, &show_help, 1},
145   {"version", no_argument, &show_version, 1},
146   {NULL, 0, NULL, 0}
147 };
148
149 void
150 main (argc, argv)
151      int argc;
152      char **argv;
153 {
154   enum header_mode header_mode = multiple_files;
155   int exit_status = 0;
156   /* If from_start, the number of items to skip before printing; otherwise,
157      the number of items at the end of the file to print.  Initially, -1
158      means the value has not been set.  */
159   off_t n_units = -1;
160   long int tmp_long;
161   int c;                        /* Option character.  */
162   int fileind;                  /* Index in ARGV of first file name.  */
163
164   program_name = argv[0];
165   have_read_stdin = 0;
166   count_lines = 1;
167   forever = forever_multiple = from_start = print_headers = 0;
168
169   if (argc > 1
170       && ((argv[1][0] == '-' && ISDIGIT (argv[1][1]))
171           || (argv[1][0] == '+' && (ISDIGIT (argv[1][1]) || argv[1][1] == 0))))
172     {
173       /* Old option syntax: a dash or plus, one or more digits (zero digits
174          are acceptable with a plus), and one or more option letters.  */
175       if (argv[1][0] == '+')
176         from_start = 1;
177       if (argv[1][1] != '\0')
178         {
179           strtol_error s_err;
180           char *p;
181
182           s_err = xstrtol (++argv[1], &p, 0, &tmp_long, "bkm");
183           n_units = tmp_long;
184           if (s_err == LONGINT_OVERFLOW)
185             {
186               STRTOL_FATAL_ERROR (argv[1], "argument", s_err);
187             }
188           /* Parse any appended option letters.  */
189           while (*p)
190             {
191               switch (*p)
192                 {
193                 case 'c':
194                   /* Interpret N_UNITS as # of bytes.  */
195                   count_lines = 0;
196                   break;
197
198                 case 'f':
199                   forever = 1;
200                   break;
201
202                 case 'l':
203                   count_lines = 1;
204                   break;
205
206                 case 'q':
207                   header_mode = never;
208                   break;
209
210                 case 'v':
211                   header_mode = always;
212                   break;
213
214                 default:
215                   error (0, 0, "unrecognized option `-%c'", *p);
216                   usage (1);
217                 }
218               ++p;
219             }
220         }
221       /* Make the options we just parsed invisible to getopt.  */
222       argv[1] = argv[0];
223       argv++;
224       argc--;
225     }
226
227   while ((c = getopt_long (argc, argv, "c:n:fqv", long_options, (int *) 0))
228          != EOF)
229     {
230       int allow_bkm_suffix;
231       strtol_error s_err;
232
233       switch (c)
234         {
235         case 0:
236           break;
237
238         case 'c':
239           count_lines = 0;
240           allow_bkm_suffix = 1;
241           goto getnum;
242
243         case 'n':
244           count_lines = 1;
245           allow_bkm_suffix = 0;
246         getnum:
247           if (*optarg == '+')
248             {
249               from_start = 1;
250             }
251
252           s_err = xstrtol (optarg, NULL, 0, &tmp_long, "bkm");
253           if (tmp_long < 0)
254             tmp_long = -tmp_long;
255           n_units = tmp_long;
256           if (s_err != LONGINT_OK)
257             {
258               STRTOL_FATAL_ERROR (optarg, (c == 'n'
259                                            ? "number of lines"
260                                            : "number of bytes"), s_err);
261             }
262           break;
263
264         case 'f':
265           forever = 1;
266           break;
267
268         case 'q':
269           header_mode = never;
270           break;
271
272         case 'v':
273           header_mode = always;
274           break;
275
276         default:
277           usage (1);
278         }
279     }
280
281   if (show_version)
282     {
283       printf ("tail - %s\n", version_string);
284       exit (0);
285     }
286
287   if (show_help)
288     usage (0);
289
290   if (n_units == -1)
291     n_units = DEFAULT_N_LINES;
292
293   /* To start printing with item N_UNITS from the start of the file, skip
294      N_UNITS - 1 items.  `tail +0' is actually meaningless, but for Unix
295      compatibility it's treated the same as `tail +1'.  */
296   if (from_start)
297     {
298       if (n_units)
299         --n_units;
300     }
301
302   fileind = optind;
303
304   if (optind < argc - 1 && forever)
305     {
306       forever_multiple = 1;
307       forever = 0;
308       file_descs = (int *) xmalloc ((argc - optind) * sizeof (int));
309       file_sizes = (off_t *) xmalloc ((argc - optind) * sizeof (off_t));
310     }
311
312   if (header_mode == always
313       || (header_mode == multiple_files && optind < argc - 1))
314     print_headers = 1;
315
316   if (optind == argc)
317     exit_status |= tail_file ("-", n_units, 0);
318
319   for (; optind < argc; ++optind)
320     exit_status |= tail_file (argv[optind], n_units, optind - fileind);
321
322   if (forever_multiple)
323     tail_forever (argv + fileind, argc - fileind);
324
325   if (have_read_stdin && close (0) < 0)
326     error (1, errno, "-");
327   if (fclose (stdout) == EOF)
328     error (1, errno, "write error");
329   exit (exit_status);
330 }
331
332 /* Display the last N_UNITS units of file FILENAME.
333    "-" for FILENAME means the standard input.
334    FILENUM is this file's index in the list of files the user gave.
335    Return 0 if successful, 1 if an error occurred.  */
336
337 static int
338 tail_file (filename, n_units, filenum)
339      const char *filename;
340      off_t n_units;
341      int filenum;
342 {
343   int fd, errors;
344   struct stat stats;
345
346   if (!strcmp (filename, "-"))
347     {
348       have_read_stdin = 1;
349       filename = "standard input";
350       if (print_headers)
351         write_header (filename, NULL);
352       errors = tail (filename, 0, n_units);
353       if (forever_multiple)
354         {
355           if (fstat (0, &stats) < 0)
356             {
357               error (0, errno, "standard input");
358               errors = 1;
359             }
360           else if (!S_ISREG (stats.st_mode))
361             {
362               error (0, 0,
363                      "standard input: cannot follow end of non-regular file");
364               errors = 1;
365             }
366           if (errors)
367             file_descs[filenum] = -1;
368           else
369             {
370               file_descs[filenum] = 0;
371               file_sizes[filenum] = stats.st_size;
372             }
373         }
374     }
375   else
376     {
377       /* Not standard input.  */
378       fd = open (filename, O_RDONLY);
379       if (fd == -1)
380         {
381           if (forever_multiple)
382             file_descs[filenum] = -1;
383           error (0, errno, "%s", filename);
384           errors = 1;
385         }
386       else
387         {
388           if (print_headers)
389             write_header (filename, NULL);
390           errors = tail (filename, fd, n_units);
391           if (forever_multiple)
392             {
393               if (fstat (fd, &stats) < 0)
394                 {
395                   error (0, errno, "%s", filename);
396                   errors = 1;
397                 }
398               else if (!S_ISREG (stats.st_mode))
399                 {
400                   error (0, 0, "%s: cannot follow end of non-regular file",
401                          filename);
402                   errors = 1;
403                 }
404               if (errors)
405                 {
406                   close (fd);
407                   file_descs[filenum] = -1;
408                 }
409               else
410                 {
411                   file_descs[filenum] = fd;
412                   file_sizes[filenum] = stats.st_size;
413                 }
414             }
415           else
416             {
417               if (close (fd))
418                 {
419                   error (0, errno, "%s", filename);
420                   errors = 1;
421                 }
422             }
423         }
424     }
425
426   return errors;
427 }
428
429 static void
430 write_header (filename, comment)
431      const char *filename;
432      const char *comment;
433 {
434   static int first_file = 1;
435
436   printf ("%s==> %s%s%s <==\n", (first_file ? "" : "\n"), filename,
437           (comment ? ": " : ""),
438           (comment ? comment : ""));
439   first_file = 0;
440 }
441
442 /* Display the last N_UNITS units of file FILENAME, open for reading
443    in FD.
444    Return 0 if successful, 1 if an error occurred.  */
445
446 static int
447 tail (filename, fd, n_units)
448      const char *filename;
449      int fd;
450      off_t n_units;
451 {
452   if (count_lines)
453     return tail_lines (filename, fd, n_units);
454   else
455     return tail_bytes (filename, fd, n_units);
456 }
457
458 /* Output the last N_BYTES bytes of file FILENAME open for reading in FD.
459    Return 0 if successful, 1 if an error occurred.  */
460
461 static int
462 tail_bytes (filename, fd, n_bytes)
463      const char *filename;
464      int fd;
465      off_t n_bytes;
466 {
467   struct stat stats;
468
469   /* FIXME: resolve this like in dd.c.  */
470   /* Use fstat instead of checking for errno == ESPIPE because
471      lseek doesn't work on some special files but doesn't return an
472      error, either.  */
473   if (fstat (fd, &stats))
474     {
475       error (0, errno, "%s", filename);
476       return 1;
477     }
478
479   if (from_start)
480     {
481       if (S_ISREG (stats.st_mode))
482         lseek (fd, n_bytes, SEEK_SET);
483       else if (start_bytes (filename, fd, n_bytes))
484         return 1;
485       dump_remainder (filename, fd);
486     }
487   else
488     {
489       if (S_ISREG (stats.st_mode))
490         {
491           if (lseek (fd, (off_t) 0, SEEK_END) <= n_bytes)
492             /* The file is shorter than we want, or just the right size, so
493                print the whole file.  */
494             lseek (fd, (off_t) 0, SEEK_SET);
495           else
496             /* The file is longer than we want, so go back.  */
497             lseek (fd, -n_bytes, SEEK_END);
498           dump_remainder (filename, fd);
499         }
500       else
501         return pipe_bytes (filename, fd, n_bytes);
502     }
503   return 0;
504 }
505
506 /* Output the last N_LINES lines of file FILENAME open for reading in FD.
507    Return 0 if successful, 1 if an error occurred.  */
508
509 static int
510 tail_lines (filename, fd, n_lines)
511      const char *filename;
512      int fd;
513      long n_lines;
514 {
515   struct stat stats;
516   long length;
517
518   if (fstat (fd, &stats))
519     {
520       error (0, errno, "%s", filename);
521       return 1;
522     }
523
524   if (from_start)
525     {
526       if (start_lines (filename, fd, n_lines))
527         return 1;
528       dump_remainder (filename, fd);
529     }
530   else
531     {
532       if (S_ISREG (stats.st_mode))
533         {
534           length = lseek (fd, (off_t) 0, SEEK_END);
535           if (length != 0 && file_lines (filename, fd, n_lines, length))
536             return 1;
537           dump_remainder (filename, fd);
538         }
539       else
540         return pipe_lines (filename, fd, n_lines);
541     }
542   return 0;
543 }
544
545 /* Print the last N_LINES lines from the end of file FD.
546    Go backward through the file, reading `BUFSIZ' bytes at a time (except
547    probably the first), until we hit the start of the file or have
548    read NUMBER newlines.
549    POS starts out as the length of the file (the offset of the last
550    byte of the file + 1).
551    Return 0 if successful, 1 if an error occurred.  */
552
553 static int
554 file_lines (filename, fd, n_lines, pos)
555      const char *filename;
556      int fd;
557      long n_lines;
558      off_t pos;
559 {
560   char buffer[BUFSIZ];
561   int bytes_read;
562   int i;                        /* Index into `buffer' for scanning.  */
563
564   if (n_lines == 0)
565     return 0;
566
567   /* Set `bytes_read' to the size of the last, probably partial, buffer;
568      0 < `bytes_read' <= `BUFSIZ'.  */
569   bytes_read = pos % BUFSIZ;
570   if (bytes_read == 0)
571     bytes_read = BUFSIZ;
572   /* Make `pos' a multiple of `BUFSIZ' (0 if the file is short), so that all
573      reads will be on block boundaries, which might increase efficiency.  */
574   pos -= bytes_read;
575   lseek (fd, pos, SEEK_SET);
576   bytes_read = safe_read (fd, buffer, bytes_read);
577   if (bytes_read == -1)
578     {
579       error (0, errno, "%s", filename);
580       return 1;
581     }
582
583   /* Count the incomplete line on files that don't end with a newline.  */
584   if (bytes_read && buffer[bytes_read - 1] != '\n')
585     --n_lines;
586
587   do
588     {
589       /* Scan backward, counting the newlines in this bufferfull.  */
590       for (i = bytes_read - 1; i >= 0; i--)
591         {
592           /* Have we counted the requested number of newlines yet?  */
593           if (buffer[i] == '\n' && n_lines-- == 0)
594             {
595               /* If this newline wasn't the last character in the buffer,
596                  print the text after it.  */
597               if (i != bytes_read - 1)
598                 XWRITE (STDOUT_FILENO, &buffer[i + 1], bytes_read - (i + 1));
599               return 0;
600             }
601         }
602       /* Not enough newlines in that bufferfull.  */
603       if (pos == 0)
604         {
605           /* Not enough lines in the file; print the entire file.  */
606           lseek (fd, (off_t) 0, SEEK_SET);
607           return 0;
608         }
609       pos -= BUFSIZ;
610       lseek (fd, pos, SEEK_SET);
611     }
612   while ((bytes_read = safe_read (fd, buffer, BUFSIZ)) > 0);
613   if (bytes_read == -1)
614     {
615       error (0, errno, "%s", filename);
616       return 1;
617     }
618   return 0;
619 }
620
621 /* Print the last N_LINES lines from the end of the standard input,
622    open for reading as pipe FD.
623    Buffer the text as a linked list of LBUFFERs, adding them as needed.
624    Return 0 if successful, 1 if an error occured.  */
625
626 static int
627 pipe_lines (filename, fd, n_lines)
628      const char *filename;
629      int fd;
630      long n_lines;
631 {
632   struct linebuffer
633   {
634     int nbytes, nlines;
635     char buffer[BUFSIZ];
636     struct linebuffer *next;
637   };
638   typedef struct linebuffer LBUFFER;
639   LBUFFER *first, *last, *tmp;
640   int i;                        /* Index into buffers.  */
641   int total_lines = 0;          /* Total number of newlines in all buffers.  */
642   int errors = 0;
643
644   first = last = (LBUFFER *) xmalloc (sizeof (LBUFFER));
645   first->nbytes = first->nlines = 0;
646   first->next = NULL;
647   tmp = (LBUFFER *) xmalloc (sizeof (LBUFFER));
648
649   /* Input is always read into a fresh buffer.  */
650   while ((tmp->nbytes = safe_read (fd, tmp->buffer, BUFSIZ)) > 0)
651     {
652       tmp->nlines = 0;
653       tmp->next = NULL;
654
655       /* Count the number of newlines just read.  */
656       for (i = 0; i < tmp->nbytes; i++)
657         if (tmp->buffer[i] == '\n')
658           ++tmp->nlines;
659       total_lines += tmp->nlines;
660
661       /* If there is enough room in the last buffer read, just append the new
662          one to it.  This is because when reading from a pipe, `nbytes' can
663          often be very small.  */
664       if (tmp->nbytes + last->nbytes < BUFSIZ)
665         {
666           memcpy (&last->buffer[last->nbytes], tmp->buffer, tmp->nbytes);
667           last->nbytes += tmp->nbytes;
668           last->nlines += tmp->nlines;
669         }
670       else
671         {
672           /* If there's not enough room, link the new buffer onto the end of
673              the list, then either free up the oldest buffer for the next
674              read if that would leave enough lines, or else malloc a new one.
675              Some compaction mechanism is possible but probably not
676              worthwhile.  */
677           last = last->next = tmp;
678           if (total_lines - first->nlines > n_lines)
679             {
680               tmp = first;
681               total_lines -= first->nlines;
682               first = first->next;
683             }
684           else
685             tmp = (LBUFFER *) xmalloc (sizeof (LBUFFER));
686         }
687     }
688   if (tmp->nbytes == -1)
689     {
690       error (0, errno, "%s", filename);
691       errors = 1;
692       free ((char *) tmp);
693       goto free_lbuffers;
694     }
695
696   free ((char *) tmp);
697
698   /* This prevents a core dump when the pipe contains no newlines.  */
699   if (n_lines == 0)
700     goto free_lbuffers;
701
702   /* Count the incomplete line on files that don't end with a newline.  */
703   if (last->buffer[last->nbytes - 1] != '\n')
704     {
705       ++last->nlines;
706       ++total_lines;
707     }
708
709   /* Run through the list, printing lines.  First, skip over unneeded
710      buffers.  */
711   for (tmp = first; total_lines - tmp->nlines > n_lines; tmp = tmp->next)
712     total_lines -= tmp->nlines;
713
714   /* Find the correct beginning, then print the rest of the file.  */
715   if (total_lines > n_lines)
716     {
717       char *cp;
718
719       /* Skip `total_lines' - `n_lines' newlines.  We made sure that
720          `total_lines' - `n_lines' <= `tmp->nlines'.  */
721       cp = tmp->buffer;
722       for (i = total_lines - n_lines; i; --i)
723         while (*cp++ != '\n')
724           /* Do nothing.  */ ;
725       i = cp - tmp->buffer;
726     }
727   else
728     i = 0;
729   XWRITE (STDOUT_FILENO, &tmp->buffer[i], tmp->nbytes - i);
730
731   for (tmp = tmp->next; tmp; tmp = tmp->next)
732     XWRITE (STDOUT_FILENO, tmp->buffer, tmp->nbytes);
733
734 free_lbuffers:
735   while (first)
736     {
737       tmp = first->next;
738       free ((char *) first);
739       first = tmp;
740     }
741   return errors;
742 }
743
744 /* Print the last N_BYTES characters from the end of pipe FD.
745    This is a stripped down version of pipe_lines.
746    Return 0 if successful, 1 if an error occurred.  */
747
748 static int
749 pipe_bytes (filename, fd, n_bytes)
750      const char *filename;
751      int fd;
752      off_t n_bytes;
753 {
754   struct charbuffer
755   {
756     int nbytes;
757     char buffer[BUFSIZ];
758     struct charbuffer *next;
759   };
760   typedef struct charbuffer CBUFFER;
761   CBUFFER *first, *last, *tmp;
762   int i;                        /* Index into buffers.  */
763   int total_bytes = 0;          /* Total characters in all buffers.  */
764   int errors = 0;
765
766   first = last = (CBUFFER *) xmalloc (sizeof (CBUFFER));
767   first->nbytes = 0;
768   first->next = NULL;
769   tmp = (CBUFFER *) xmalloc (sizeof (CBUFFER));
770
771   /* Input is always read into a fresh buffer.  */
772   while ((tmp->nbytes = safe_read (fd, tmp->buffer, BUFSIZ)) > 0)
773     {
774       tmp->next = NULL;
775
776       total_bytes += tmp->nbytes;
777       /* If there is enough room in the last buffer read, just append the new
778          one to it.  This is because when reading from a pipe, `nbytes' can
779          often be very small.  */
780       if (tmp->nbytes + last->nbytes < BUFSIZ)
781         {
782           memcpy (&last->buffer[last->nbytes], tmp->buffer, tmp->nbytes);
783           last->nbytes += tmp->nbytes;
784         }
785       else
786         {
787           /* If there's not enough room, link the new buffer onto the end of
788              the list, then either free up the oldest buffer for the next
789              read if that would leave enough characters, or else malloc a new
790              one.  Some compaction mechanism is possible but probably not
791              worthwhile.  */
792           last = last->next = tmp;
793           if (total_bytes - first->nbytes > n_bytes)
794             {
795               tmp = first;
796               total_bytes -= first->nbytes;
797               first = first->next;
798             }
799           else
800             {
801               tmp = (CBUFFER *) xmalloc (sizeof (CBUFFER));
802             }
803         }
804     }
805   if (tmp->nbytes == -1)
806     {
807       error (0, errno, "%s", filename);
808       errors = 1;
809       free ((char *) tmp);
810       goto free_cbuffers;
811     }
812
813   free ((char *) tmp);
814
815   /* Run through the list, printing characters.  First, skip over unneeded
816      buffers.  */
817   for (tmp = first; total_bytes - tmp->nbytes > n_bytes; tmp = tmp->next)
818     total_bytes -= tmp->nbytes;
819
820   /* Find the correct beginning, then print the rest of the file.
821      We made sure that `total_bytes' - `n_bytes' <= `tmp->nbytes'.  */
822   if (total_bytes > n_bytes)
823     i = total_bytes - n_bytes;
824   else
825     i = 0;
826   XWRITE (STDOUT_FILENO, &tmp->buffer[i], tmp->nbytes - i);
827
828   for (tmp = tmp->next; tmp; tmp = tmp->next)
829     XWRITE (STDOUT_FILENO, tmp->buffer, tmp->nbytes);
830
831 free_cbuffers:
832   while (first)
833     {
834       tmp = first->next;
835       free ((char *) first);
836       first = tmp;
837     }
838   return errors;
839 }
840
841 /* Skip N_BYTES characters from the start of pipe FD, and print
842    any extra characters that were read beyond that.
843    Return 1 on error, 0 if ok.  */
844
845 static int
846 start_bytes (filename, fd, n_bytes)
847      const char *filename;
848      int fd;
849      off_t n_bytes;
850 {
851   char buffer[BUFSIZ];
852   int bytes_read = 0;
853
854   while (n_bytes > 0 && (bytes_read = safe_read (fd, buffer, BUFSIZ)) > 0)
855     n_bytes -= bytes_read;
856   if (bytes_read == -1)
857     {
858       error (0, errno, "%s", filename);
859       return 1;
860     }
861   else if (n_bytes < 0)
862     XWRITE (STDOUT_FILENO, &buffer[bytes_read + n_bytes], -n_bytes);
863   return 0;
864 }
865
866 /* Skip N_LINES lines at the start of file or pipe FD, and print
867    any extra characters that were read beyond that.
868    Return 1 on error, 0 if ok.  */
869
870 static int
871 start_lines (filename, fd, n_lines)
872      const char *filename;
873      int fd;
874      long n_lines;
875 {
876   char buffer[BUFSIZ];
877   int bytes_read = 0;
878   int bytes_to_skip = 0;
879
880   while (n_lines && (bytes_read = safe_read (fd, buffer, BUFSIZ)) > 0)
881     {
882       bytes_to_skip = 0;
883       while (bytes_to_skip < bytes_read)
884         if (buffer[bytes_to_skip++] == '\n' && --n_lines == 0)
885           break;
886     }
887   if (bytes_read == -1)
888     {
889       error (0, errno, "%s", filename);
890       return 1;
891     }
892   else if (bytes_to_skip < bytes_read)
893     {
894       XWRITE (STDOUT_FILENO, &buffer[bytes_to_skip],
895               bytes_read - bytes_to_skip);
896     }
897   return 0;
898 }
899
900 /* Display file FILENAME from the current position in FD to the end.
901    If `forever' is nonzero, keep reading from the end of the file
902    until killed.  Return the number of bytes read from the file.  */
903
904 static long
905 dump_remainder (filename, fd)
906      const char *filename;
907      int fd;
908 {
909   char buffer[BUFSIZ];
910   int bytes_read;
911   long total;
912
913   total = 0;
914 output:
915   while ((bytes_read = safe_read (fd, buffer, BUFSIZ)) > 0)
916     {
917       XWRITE (STDOUT_FILENO, buffer, bytes_read);
918       total += bytes_read;
919     }
920   if (bytes_read == -1)
921     error (1, errno, "%s", filename);
922   if (forever)
923     {
924       fflush (stdout);
925       sleep (1);
926       goto output;
927     }
928   return total;
929 }
930
931 /* Tail NFILES (>1) files forever until killed.  The file names are in
932    NAMES.  The open file descriptors are in `file_descs', and the size
933    at which we stopped tailing them is in `file_sizes'.  We loop over
934    each of them, doing an fstat to see if they have changed size.  If
935    none of them have changed size in one iteration, we sleep for a
936    second and try again.  We do this until the user interrupts us.  */
937
938 static void
939 tail_forever (names, nfiles)
940      char **names;
941      int nfiles;
942 {
943   int last;
944
945   last = -1;
946
947   while (1)
948     {
949       int i;
950       int changed;
951
952       changed = 0;
953       for (i = 0; i < nfiles; i++)
954         {
955           struct stat stats;
956
957           if (file_descs[i] < 0)
958             continue;
959           if (fstat (file_descs[i], &stats) < 0)
960             {
961               error (0, errno, "%s", names[i]);
962               file_descs[i] = -1;
963               continue;
964             }
965           if (stats.st_size == file_sizes[i])
966             continue;
967
968           /* This file has changed size.  Print out what we can, and
969              then keep looping.  */
970
971           changed = 1;
972
973           if (stats.st_size < file_sizes[i])
974             {
975               write_header (names[i], "file truncated");
976               last = i;
977               lseek (file_descs[i], stats.st_size, SEEK_SET);
978               file_sizes[i] = stats.st_size;
979               continue;
980             }
981
982           if (i != last)
983             {
984               if (print_headers)
985                 write_header (names[i], NULL);
986               last = i;
987             }
988           file_sizes[i] += dump_remainder (names[i], file_descs[i]);
989         }
990
991       /* If none of the files changed size, sleep.  */
992       if (! changed)
993         sleep (1);
994     }
995 }
996
997 static void
998 usage (status)
999      int status;
1000 {
1001   if (status != 0)
1002     fprintf (stderr, "Try `%s --help' for more information.\n",
1003              program_name);
1004   else
1005     {
1006       printf ("\
1007 Usage: %s [OPTION]... [FILE]...\n\
1008 ",
1009               program_name);
1010       printf ("\
1011 \n\
1012   -c, --bytes=N            output the last N bytes\n\
1013   -f, --follow             output appended data as the file grows\n\
1014   -n, --lines=N            output the last N lines, instead of last 10\n\
1015   -q, --quiet, --silent    never output headers giving file names\n\
1016   -v, --verbose            always output headers giving file names\n\
1017       --help               display this help and exit\n\
1018       --version            output version information and exit\n\
1019 \n\
1020 If the first character of N (the number of bytes or lines) is a `+',\n\
1021 print beginning with the Nth item from the start of each file, otherwise,\n\
1022 print the last N items in the file.  N may have a multiplier suffix:\n\
1023 b for 512, k for 1024, m for 1048576 (1 Meg).  A first OPTION of -VALUE\n\
1024 or +VALUE is treated like -n VALUE or -n +VALUE unless VALUE has one of\n\
1025 the [bkm] suffix multipliers, in which case it is treated like -c VALUE\n\
1026 or -c +VALUE.  With no FILE, or when FILE is -, read standard input.\n\
1027 ");
1028     }
1029   exit (status);
1030 }