home *** CD-ROM | disk | FTP | other *** search
/ Fresh Fish 1 / FFMCD01.bin / useful / dist / gnu / textutils / textutils-1.6-amiga / src / tail.c < prev    next >
Encoding:
C/C++ Source or Header  |  1993-05-15  |  24.0 KB  |  1,016 lines

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