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