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