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