home *** CD-ROM | disk | FTP | other *** search
/ Fresh Fish 9 / FreshFishVol9-CD2.bin / bbs / gnu / textutils-1.11-src.lha / textutils-1.11 / src / cat.c next >
Encoding:
C/C++ Source or Header  |  1994-11-13  |  17.0 KB  |  729 lines

  1. /* cat -- concatenate files and print on the standard output.
  2.    Copyright (C) 1988, 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. /* Differences from the Unix cat:
  19.    * Always unbuffered, -u is ignored.
  20.    * 100 times faster with -v -u.
  21.    * 20 times faster with -v.
  22.  
  23.    By tege@sics.se, Torbjorn Granlund, advised by rms, Richard Stallman. */
  24.  
  25. #include <config.h>
  26.  
  27. #include <stdio.h>
  28. #include <getopt.h>
  29. #include <sys/types.h>
  30. #ifndef _POSIX_SOURCE
  31. #include <sys/ioctl.h>
  32. #endif
  33. #include "system.h"
  34. #include "version.h"
  35.  
  36. #define max(h,i) ((h) > (i) ? (h) : (i))
  37.  
  38. char *stpcpy ();
  39. char *xmalloc ();
  40. void error ();
  41. int full_write ();
  42. int safe_read ();
  43.  
  44. static void cat ();
  45. static void next_line_num ();
  46. static void simple_cat ();
  47.  
  48. /* Name under which this program was invoked.  */
  49. char *program_name;
  50.  
  51. /* Name of input file.  May be "-".  */
  52. static char *infile;
  53.  
  54. /* Descriptor on which input file is open.  */
  55. static int input_desc;
  56.  
  57. /* Descriptor on which output file is open.  Always is 1.  */
  58. static int output_desc;
  59.  
  60. /* Buffer for line numbers.  */
  61. static char line_buf[13] =
  62. {' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '0', '\t', '\0'};
  63.  
  64. /* Position in `line_buf' where printing starts.  This will not change
  65.    unless the number of lines is larger than 999999.  */
  66. static char *line_num_print = line_buf + 5;
  67.  
  68. /* Position of the first digit in `line_buf'.  */
  69. static char *line_num_start = line_buf + 10;
  70.  
  71. /* Position of the last digit in `line_buf'.  */
  72. static char *line_num_end = line_buf + 10;
  73.  
  74. /* Preserves the `cat' function's local `newlines' between invocations.  */
  75. static int newlines2 = 0;
  76.  
  77. /* Count of non-fatal error conditions.  */
  78. static int exit_stat = 0;
  79.  
  80. static void
  81. usage (status)
  82.      int status;
  83. {
  84.   if (status != 0)
  85.     fprintf (stderr, "Try `%s --help' for more information.\n",
  86.          program_name);
  87.   else
  88.     {
  89.       printf ("\
  90. Usage: %s [OPTION] [FILE]...\n\
  91. ",
  92.           program_name);
  93.       printf ("\
  94. \n\
  95.   -b, --number-nonblank    number nonblank output lines\n\
  96.   -e                       equivalent to -vE\n\
  97.   -n, --number             number all output lines\n\
  98.   -s, --squeeze-blank      never more than one single blank line\n\
  99.   -t                       equivalent to -vT\n\
  100.   -u                       (ignored)\n\
  101.   -v, --show-nonprinting   use ^ and M- notation, save for LFD and TAB\n\
  102.   -A, --show-all           equivalent to -vET\n\
  103.   -E, --show-ends          display $ at end of each line\n\
  104.   -T, --show-tabs          display TAB characters as ^I\n\
  105.       --help               display this help and exit\n\
  106.       --version            output version information and exit\n\
  107. \n\
  108. With no FILE, or when FILE is -, read standard input.\n\
  109. ");
  110.     }
  111.   exit (status);
  112. }
  113.  
  114.  
  115. main (argc, argv)
  116.      int argc;
  117.      char *argv[];
  118. {
  119.   /* Optimal size of i/o operations of output.  */
  120.   int outsize;
  121.  
  122.   /* Optimal size of i/o operations of input.  */
  123.   int insize;
  124.  
  125.   /* Pointer to the input buffer.  */
  126.   unsigned char *inbuf;
  127.  
  128.   /* Pointer to the output buffer.  */
  129.   unsigned char *outbuf;
  130.  
  131.   int c;
  132.  
  133.   /* Index in argv to processed argument.  */
  134.   int argind;
  135.  
  136.   /* Device number of the output (file or whatever).  */
  137.   int out_dev;
  138.  
  139.   /* I-node number of the output.  */
  140.   int out_ino;
  141.  
  142.   /* Nonzero if the output file should not be the same as any input file. */
  143.   int check_redirection = 1;
  144.  
  145.   /* Nonzero if we have ever read standard input. */
  146.   int have_read_stdin = 0;
  147.  
  148.   struct stat stat_buf;
  149.  
  150.   /* Variables that are set according to the specified options.  */
  151.   int numbers = 0;
  152.   int numbers_at_empty_lines = 1;
  153.   int squeeze_empty_lines = 0;
  154.   int mark_line_ends = 0;
  155.   int quote = 0;
  156.   int output_tabs = 1;
  157.  
  158. /* If non-zero, call cat, otherwise call simple_cat to do the actual work. */
  159.   int options = 0;
  160.  
  161.   /* If non-zero, display usage information and exit.  */
  162.   static int show_help;
  163.  
  164.   /* If non-zero, print the version on standard output then exit.  */
  165.   static int show_version;
  166.  
  167.   static struct option const long_options[] =
  168.   {
  169.     {"number-nonblank", no_argument, NULL, 'b'},
  170.     {"number", no_argument, NULL, 'n'},
  171.     {"squeeze-blank", no_argument, NULL, 's'},
  172.     {"show-nonprinting", no_argument, NULL, 'v'},
  173.     {"show-ends", no_argument, NULL, 'E'},
  174.     {"show-tabs", no_argument, NULL, 'T'},
  175.     {"show-all", no_argument, NULL, 'A'},
  176.     {"help", no_argument, &show_help, 1},
  177.     {"version", no_argument, &show_version, 1},
  178.     {NULL, 0, NULL, 0}
  179.   };
  180.  
  181.   program_name = argv[0];
  182.  
  183.   /* Parse command line options.  */
  184.  
  185.   while ((c = getopt_long (argc, argv, "benstuvAET", long_options, (int *) 0))
  186.      != EOF)
  187.     {
  188.       switch (c)
  189.     {
  190.     case 0:
  191.       break;
  192.  
  193.     case 'b':
  194.       ++options;
  195.       numbers = 1;
  196.       numbers_at_empty_lines = 0;
  197.       break;
  198.  
  199.     case 'e':
  200.       ++options;
  201.       mark_line_ends = 1;
  202.       quote = 1;
  203.       break;
  204.  
  205.     case 'n':
  206.       ++options;
  207.       numbers = 1;
  208.       break;
  209.  
  210.     case 's':
  211.       ++options;
  212.       squeeze_empty_lines = 1;
  213.       break;
  214.  
  215.     case 't':
  216.       ++options;
  217.       output_tabs = 0;
  218.       quote = 1;
  219.       break;
  220.  
  221.     case 'u':
  222.       /* We provide the -u feature unconditionally.  */
  223.       break;
  224.  
  225.     case 'v':
  226.       ++options;
  227.       quote = 1;
  228.       break;
  229.  
  230.     case 'A':
  231.       ++options;
  232.       quote = 1;
  233.       mark_line_ends = 1;
  234.       output_tabs = 0;
  235.       break;
  236.  
  237.     case 'E':
  238.       ++options;
  239.       mark_line_ends = 1;
  240.       break;
  241.  
  242.     case 'T':
  243.       ++options;
  244.       output_tabs = 0;
  245.       break;
  246.  
  247.     default:
  248.       usage (2);
  249.     }
  250.     }
  251.  
  252.   if (show_version)
  253.     {
  254.       printf ("cat - %s\n", version_string);
  255.       exit (0);
  256.     }
  257.  
  258.   if (show_help)
  259.     usage (0);
  260.  
  261.   output_desc = 1;
  262.  
  263.   /* Get device, i-node number, and optimal blocksize of output.  */
  264.  
  265.   if (fstat (output_desc, &stat_buf) < 0)
  266.     error (1, errno, "standard output");
  267.  
  268.   outsize = ST_BLKSIZE (stat_buf);
  269.   /* Input file can be output file for non-regular files.
  270.      fstat on pipes returns S_IFSOCK on some systems, S_IFIFO
  271.      on others, so the checking should not be done for those types,
  272.      and to allow things like cat < /dev/tty > /dev/tty, checking
  273.      is not done for device files either. */
  274.  
  275.   if (S_ISREG (stat_buf.st_mode))
  276.     {
  277.       out_dev = stat_buf.st_dev;
  278.       out_ino = stat_buf.st_ino;
  279.     }
  280.   else
  281.     {
  282.       check_redirection = 0;
  283. #ifdef lint  /* Suppress `used before initialized' warning.  */
  284.       out_dev = 0;
  285.       out_ino = 0;
  286. #endif
  287.     }
  288.  
  289.   /* Check if any of the input files are the same as the output file.  */
  290.  
  291.   /* Main loop.  */
  292.  
  293.   infile = "-";
  294.   argind = optind;
  295.  
  296.   do
  297.     {
  298.       if (argind < argc)
  299.     infile = argv[argind];
  300.  
  301.       if (infile[0] == '-' && infile[1] == 0)
  302.     {
  303.       have_read_stdin = 1;
  304.       input_desc = 0;
  305.     }
  306.       else
  307.     {
  308.       input_desc = open (infile, O_RDONLY);
  309.       if (input_desc < 0)
  310.         {
  311.           error (0, errno, "%s", infile);
  312.           exit_stat = 1;
  313.           continue;
  314.         }
  315.     }
  316.  
  317.       if (fstat (input_desc, &stat_buf) < 0)
  318.     {
  319.       error (0, errno, "%s", infile);
  320.       exit_stat = 1;
  321.       goto contin;
  322.     }
  323.       insize = ST_BLKSIZE (stat_buf);
  324.  
  325.       /* Compare the device and i-node numbers of this input file with
  326.      the corresponding values of the (output file associated with)
  327.      stdout, and skip this input file if they coincide.  Input
  328.      files cannot be redirected to themselves.  */
  329.  
  330.       if (check_redirection
  331.       && stat_buf.st_dev == out_dev && stat_buf.st_ino == out_ino)
  332.     {
  333.       error (0, 0, "%s: input file is output file", infile);
  334.       exit_stat = 1;
  335.       goto contin;
  336.     }
  337.  
  338.       /* Select which version of `cat' to use. If any options (more than -u,
  339.      --version, or --help) were specified, use `cat', otherwise use
  340.      `simple_cat'.  */
  341.  
  342.       if (options == 0)
  343.     {
  344.       insize = max (insize, outsize);
  345.       inbuf = (unsigned char *) xmalloc (insize);
  346.  
  347.       simple_cat (inbuf, insize);
  348.     }
  349.       else
  350.     {
  351.       inbuf = (unsigned char *) xmalloc (insize + 1);
  352.  
  353.       /* Why are (OUTSIZE  - 1 + INSIZE * 4 + 13) bytes allocated for
  354.          the output buffer?
  355.  
  356.          A test whether output needs to be written is done when the input
  357.          buffer empties or when a newline appears in the input.  After
  358.          output is written, at most (OUTSIZE - 1) bytes will remain in the
  359.          buffer.  Now INSIZE bytes of input is read.  Each input character
  360.          may grow by a factor of 4 (by the prepending of M-^).  If all
  361.          characters do, and no newlines appear in this block of input, we
  362.          will have at most (OUTSIZE - 1 + INSIZE) bytes in the buffer.  If
  363.          the last character in the preceding block of input was a
  364.          newline, a line number may be written (according to the given
  365.          options) as the first thing in the output buffer. (Done after the
  366.          new input is read, but before processing of the input begins.)  A
  367.          line number requires seldom more than 13 positions.  */
  368.  
  369.       outbuf = (unsigned char *) xmalloc (outsize - 1 + insize * 4 + 13);
  370.  
  371.       cat (inbuf, insize, outbuf, outsize, quote,
  372.            output_tabs, numbers, numbers_at_empty_lines, mark_line_ends,
  373.            squeeze_empty_lines);
  374.  
  375.       free (outbuf);
  376.     }
  377.  
  378.       free (inbuf);
  379.  
  380.     contin:
  381.       if (strcmp (infile, "-") && close (input_desc) < 0)
  382.     {
  383.       error (0, errno, "%s", infile);
  384.       exit_stat = 1;
  385.     }
  386.     }
  387.   while (++argind < argc);
  388.  
  389.   if (have_read_stdin && close (0) < 0)
  390.     error (1, errno, "-");
  391.   if (close (1) < 0)
  392.     error (1, errno, "write error");
  393.  
  394.   exit (exit_stat);
  395. }
  396.  
  397. /* Plain cat.  Copies the file behind `input_desc' to the file behind
  398.    `output_desc'.  */
  399.  
  400. static void
  401. simple_cat (buf, bufsize)
  402.      /* Pointer to the buffer, used by reads and writes.  */
  403.      unsigned char *buf;
  404.  
  405.      /* Number of characters preferably read or written by each read and write
  406.         call.  */
  407.      int bufsize;
  408. {
  409.   /* Actual number of characters read, and therefore written.  */
  410.   int n_read;
  411.  
  412.   /* Loop until the end of the file.  */
  413.  
  414.   for (;;)
  415.     {
  416.       /* Read a block of input.  */
  417.  
  418.       n_read = safe_read (input_desc, buf, bufsize);
  419.       if (n_read < 0)
  420.     {
  421.       error (0, errno, "%s", infile);
  422.       exit_stat = 1;
  423.       return;
  424.     }
  425.  
  426.       /* End of this file?  */
  427.  
  428.       if (n_read == 0)
  429.     break;
  430.  
  431.       /* Write this block out.  */
  432.  
  433.       if (full_write (output_desc, buf, n_read) < 0)
  434.     error (1, errno, "write error");
  435.     }
  436. }
  437.  
  438. /* Cat the file behind INPUT_DESC to the file behind OUTPUT_DESC.
  439.    Called if any option more than -u was specified.
  440.  
  441.    A newline character is always put at the end of the buffer, to make
  442.    an explicit test for buffer end unnecessary.  */
  443.  
  444. static void
  445. cat (inbuf, insize, outbuf, outsize, quote,
  446.      output_tabs, numbers, numbers_at_empty_lines,
  447.      mark_line_ends, squeeze_empty_lines)
  448.  
  449.      /* Pointer to the beginning of the input buffer.  */
  450.      unsigned char *inbuf;
  451.  
  452.      /* Number of characters read in each read call.  */
  453.      int insize;
  454.  
  455.      /* Pointer to the beginning of the output buffer.  */
  456.      unsigned char *outbuf;
  457.  
  458.      /* Number of characters written by each write call.  */
  459.      int outsize;
  460.  
  461.      /* Variables that have values according to the specified options.  */
  462.      int quote;
  463.      int output_tabs;
  464.      int numbers;
  465.      int numbers_at_empty_lines;
  466.      int mark_line_ends;
  467.      int squeeze_empty_lines;
  468. {
  469.   /* Last character read from the input buffer.  */
  470.   unsigned char ch;
  471.  
  472.   /* Pointer to the next character in the input buffer.  */
  473.   unsigned char *bpin;
  474.  
  475.   /* Pointer to the first non-valid byte in the input buffer, i.e. the
  476.      current end of the buffer.  */
  477.   unsigned char *eob;
  478.  
  479.   /* Pointer to the position where the next character shall be written.  */
  480.   unsigned char *bpout;
  481.  
  482.   /* Number of characters read by the last read call.  */
  483.   int n_read;
  484.  
  485.   /* Determines how many consecutive newlines there have been in the
  486.      input.  0 newlines makes NEWLINES -1, 1 newline makes NEWLINES 1,
  487.      etc.  Initially 0 to indicate that we are at the beginning of a
  488.      new line.  The "state" of the procedure is determined by
  489.      NEWLINES.  */
  490.   int newlines = newlines2;
  491.  
  492. #ifdef FIONREAD
  493.   /* If nonzero, use the FIONREAD ioctl, as an optimization.
  494.      (On Ultrix, it is not supported on NFS filesystems.)  */
  495.   int use_fionread = 1;
  496. #endif
  497.  
  498.   /* The inbuf pointers are initialized so that BPIN > EOB, and thereby input
  499.      is read immediately.  */
  500.  
  501.   eob = inbuf;
  502.   bpin = eob + 1;
  503.  
  504.   bpout = outbuf;
  505.  
  506.   for (;;)
  507.     {
  508.       do
  509.     {
  510.       /* Write if there are at least OUTSIZE bytes in OUTBUF.  */
  511.  
  512.       if (bpout - outbuf >= outsize)
  513.         {
  514.           unsigned char *wp = outbuf;
  515.           do
  516.         {
  517.           if (full_write (output_desc, wp, outsize) < 0)
  518.             error (1, errno, "write error");
  519.           wp += outsize;
  520.         }
  521.           while (bpout - wp >= outsize);
  522.  
  523.           /* Move the remaining bytes to the beginning of the
  524.          buffer.  */
  525.  
  526.           bcopy (wp, outbuf, bpout - wp);
  527.           bpout = outbuf + (bpout - wp);
  528.         }
  529.  
  530.       /* Is INBUF empty?  */
  531.  
  532.       if (bpin > eob)
  533.         {
  534. #ifdef FIONREAD
  535.           int n_to_read = 0;
  536.  
  537.           /* Is there any input to read immediately?
  538.          If not, we are about to wait,
  539.          so write all buffered output before waiting.  */
  540.  
  541.           if (use_fionread
  542.           && ioctl (input_desc, FIONREAD, &n_to_read) < 0)
  543.         {
  544.           /* Ultrix returns EOPNOTSUPP on NFS;
  545.              HP-UX returns ENOTTY on pipes.
  546.              SunOS returns EINVAL and
  547.              More/BSD returns ENODEV on special files
  548.              like /dev/null.
  549.              Irix-5 returns ENOSYS on pipes.  */
  550.           if (errno == EOPNOTSUPP || errno == ENOTTY
  551.               || errno == EINVAL || errno == ENODEV
  552. #ifdef ENOSYS
  553.               || errno == ENOSYS
  554. #endif
  555.               )
  556.             use_fionread = 0;
  557.           else
  558.             {
  559.               error (0, errno, "cannot do ioctl on `%s'", infile);
  560.               exit_stat = 1;
  561.               newlines2 = newlines;
  562.               return;
  563.             }
  564.         }
  565.           if (n_to_read == 0)
  566. #endif
  567.         {
  568.           int n_write = bpout - outbuf;
  569.  
  570.           if (full_write (output_desc, outbuf, n_write) < 0)
  571.             error (1, errno, "write error");
  572.           bpout = outbuf;
  573.         }
  574.  
  575.           /* Read more input into INBUF.  */
  576.  
  577.           n_read = safe_read (input_desc, inbuf, insize);
  578.           if (n_read < 0)
  579.         {
  580.           error (0, errno, "%s", infile);
  581.           exit_stat = 1;
  582.           newlines2 = newlines;
  583.           return;
  584.         }
  585.           if (n_read == 0)
  586.         {
  587.           newlines2 = newlines;
  588.           return;
  589.         }
  590.  
  591.           /* Update the pointers and insert a sentinel at the buffer
  592.          end.  */
  593.  
  594.           bpin = inbuf;
  595.           eob = bpin + n_read;
  596.           *eob = '\n';
  597.         }
  598.       else
  599.         {
  600.           /* It was a real (not a sentinel) newline.  */
  601.  
  602.           /* Was the last line empty?
  603.          (i.e. have two or more consecutive newlines been read?)  */
  604.  
  605.           if (++newlines > 0)
  606.         {
  607.           /* Are multiple adjacent empty lines to be substituted by
  608.              single ditto (-s), and this was the second empty line?  */
  609.  
  610.           if (squeeze_empty_lines && newlines >= 2)
  611.             {
  612.               ch = *bpin++;
  613.               continue;
  614.             }
  615.  
  616.           /* Are line numbers to be written at empty lines (-n)?  */
  617.  
  618.           if (numbers && numbers_at_empty_lines)
  619.             {
  620.               next_line_num ();
  621.               bpout = (unsigned char *) stpcpy (bpout, line_num_print);
  622.             }
  623.         }
  624.  
  625.           /* Output a currency symbol if requested (-e).  */
  626.  
  627.           if (mark_line_ends)
  628.         *bpout++ = '$';
  629.  
  630.           /* Output the newline.  */
  631.  
  632.           *bpout++ = '\n';
  633.         }
  634.       ch = *bpin++;
  635.     }
  636.       while (ch == '\n');
  637.  
  638.       /* Are we at the beginning of a line, and line numbers are requested?  */
  639.  
  640.       if (newlines >= 0 && numbers)
  641.     {
  642.       next_line_num ();
  643.       bpout = (unsigned char *) stpcpy (bpout, line_num_print);
  644.     }
  645.  
  646.       /* Here CH cannot contain a newline character.  */
  647.  
  648.       /* The loops below continue until a newline character is found,
  649.      which means that the buffer is empty or that a proper newline
  650.      has been found.  */
  651.  
  652.       /* If quoting, i.e. at least one of -v, -e, or -t specified,
  653.      scan for chars that need conversion.  */
  654.       if (quote)
  655.     for (;;)
  656.       {
  657.         if (ch >= 32)
  658.           {
  659.         if (ch < 127)
  660.           *bpout++ = ch;
  661.         else if (ch == 127)
  662.           *bpout++ = '^',
  663.             *bpout++ = '?';
  664.         else
  665.           {
  666.             *bpout++ = 'M',
  667.               *bpout++ = '-';
  668.             if (ch >= 128 + 32)
  669.               if (ch < 128 + 127)
  670.             *bpout++ = ch - 128;
  671.               else
  672.             *bpout++ = '^',
  673.               *bpout++ = '?';
  674.             else
  675.               *bpout++ = '^',
  676.             *bpout++ = ch - 128 + 64;
  677.           }
  678.           }
  679.         else if (ch == '\t' && output_tabs)
  680.           *bpout++ = '\t';
  681.         else if (ch == '\n')
  682.           {
  683.         newlines = -1;
  684.         break;
  685.           }
  686.         else
  687.           *bpout++ = '^',
  688.         *bpout++ = ch + 64;
  689.  
  690.         ch = *bpin++;
  691.       }
  692.       else
  693.     /* Not quoting, neither of -v, -e, or -t specified.  */
  694.     for (;;)
  695.       {
  696.         if (ch == '\t' && !output_tabs)
  697.           *bpout++ = '^',
  698.         *bpout++ = ch + 64;
  699.         else if (ch != '\n')
  700.           *bpout++ = ch;
  701.         else
  702.           {
  703.         newlines = -1;
  704.         break;
  705.           }
  706.  
  707.         ch = *bpin++;
  708.       }
  709.     }
  710. }
  711.  
  712. /* Compute the next line number.  */
  713.  
  714. static void
  715. next_line_num ()
  716. {
  717.   char *endp = line_num_end;
  718.   do
  719.     {
  720.       if ((*endp)++ < '9')
  721.     return;
  722.       *endp-- = '0';
  723.     }
  724.   while (endp >= line_num_start);
  725.   *--line_num_start = '1';
  726.   if (line_num_start < line_num_print)
  727.     line_num_print--;
  728. }
  729.