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