.
[coreutils.git] / src / cat.c
blob76bc49c70e5446254a481a3e951f1f194149ebf2
1 /* cat -- concatenate files and print on the standard output.
2 Copyright (C) 88, 90, 91, 1995-2004 Free Software Foundation, Inc.
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.
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.
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 Foundation,
16 Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
18 /* Differences from the Unix cat:
19 * Always unbuffered, -u is ignored.
20 * Usually much faster than other versions of cat, the difference
21 is especially apparent when using the -v option.
23 By tege@sics.se, Torbjorn Granlund, advised by rms, Richard Stallman. */
25 #include <config.h>
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 "error.h"
35 #include "full-write.h"
36 #include "safe-read.h"
38 /* The official name of this program (e.g., no `g' prefix). */
39 #define PROGRAM_NAME "cat"
41 #define AUTHORS "Torbjorn Granlund", "Richard M. Stallman"
43 /* Undefine, to avoid warning about redefinition on some systems. */
44 #undef max
45 #define max(h,i) ((h) > (i) ? (h) : (i))
47 /* Name under which this program was invoked. */
48 char *program_name;
50 /* Name of input file. May be "-". */
51 static char *infile;
53 /* Descriptor on which input file is open. */
54 static int input_desc;
56 /* Buffer for line numbers.
57 An 11 digit counter may overflow within an hour on a P2/466,
58 an 18 digit counter needs about 1000y */
59 #define LINE_COUNTER_BUF_LEN 20
60 static char line_buf[LINE_COUNTER_BUF_LEN] =
62 ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
63 ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '0',
64 '\t', '\0'
67 /* Position in `line_buf' where printing starts. This will not change
68 unless the number of lines is larger than 999999. */
69 static char *line_num_print = line_buf + LINE_COUNTER_BUF_LEN - 8;
71 /* Position of the first digit in `line_buf'. */
72 static char *line_num_start = line_buf + LINE_COUNTER_BUF_LEN - 3;
74 /* Position of the last digit in `line_buf'. */
75 static char *line_num_end = line_buf + LINE_COUNTER_BUF_LEN - 3;
77 /* Preserves the `cat' function's local `newlines' between invocations. */
78 static int newlines2 = 0;
80 /* Nonzero if a non-fatal error has occurred. */
81 static int exit_status = 0;
83 void
84 usage (int status)
86 if (status != EXIT_SUCCESS)
87 fprintf (stderr, _("Try `%s --help' for more information.\n"),
88 program_name);
89 else
91 printf (_("\
92 Usage: %s [OPTION] [FILE]...\n\
93 "),
94 program_name);
95 fputs (_("\
96 Concatenate FILE(s), or standard input, to standard output.\n\
97 \n\
98 -A, --show-all equivalent to -vET\n\
99 -b, --number-nonblank number nonblank output lines\n\
100 -e equivalent to -vE\n\
101 -E, --show-ends display $ at end of each line\n\
102 -n, --number number all output lines\n\
103 -s, --squeeze-blank never more than one single blank line\n\
104 "), stdout);
105 fputs (_("\
106 -t equivalent to -vT\n\
107 -T, --show-tabs display TAB characters as ^I\n\
108 -u (ignored)\n\
109 -v, --show-nonprinting use ^ and M- notation, except for LFD and TAB\n\
110 "), stdout);
111 fputs (HELP_OPTION_DESCRIPTION, stdout);
112 fputs (VERSION_OPTION_DESCRIPTION, stdout);
113 fputs (_("\
115 With no FILE, or when FILE is -, read standard input.\n\
116 "), stdout);
117 #if O_BINARY
118 fputs (_("\
120 -B, --binary use binary writes to the console device.\n\n\
121 "), stdout);
122 #endif
123 printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
125 exit (status);
128 /* Compute the next line number. */
130 static void
131 next_line_num (void)
133 char *endp = line_num_end;
136 if ((*endp)++ < '9')
137 return;
138 *endp-- = '0';
140 while (endp >= line_num_start);
141 if (line_num_start > line_buf)
142 *--line_num_start = '1';
143 else
144 *line_buf = '>';
145 if (line_num_start < line_num_print)
146 line_num_print--;
149 /* Plain cat. Copies the file behind `input_desc' to STDOUT_FILENO. */
151 static void
152 simple_cat (
153 /* Pointer to the buffer, used by reads and writes. */
154 char *buf,
156 /* Number of characters preferably read or written by each read and write
157 call. */
158 int bufsize)
160 /* Actual number of characters read, and therefore written. */
161 size_t n_read;
163 /* Loop until the end of the file. */
165 for (;;)
167 /* Read a block of input. */
169 n_read = safe_read (input_desc, buf, bufsize);
170 if (n_read == SAFE_READ_ERROR)
172 error (0, errno, "%s", infile);
173 exit_status = 1;
174 return;
177 /* End of this file? */
179 if (n_read == 0)
180 break;
182 /* Write this block out. */
185 /* The following is ok, since we know that 0 < n_read. */
186 size_t n = n_read;
187 if (full_write (STDOUT_FILENO, buf, n) != n)
188 error (EXIT_FAILURE, errno, _("write error"));
193 /* Cat the file behind INPUT_DESC to the file behind OUTPUT_DESC.
194 Called if any option more than -u was specified.
196 A newline character is always put at the end of the buffer, to make
197 an explicit test for buffer end unnecessary. */
199 static void
200 cat (
201 /* Pointer to the beginning of the input buffer. */
202 char *inbuf,
204 /* Number of characters read in each read call. */
205 size_t insize,
207 /* Pointer to the beginning of the output buffer. */
208 char *outbuf,
210 /* Number of characters written by each write call. */
211 size_t outsize,
213 /* Variables that have values according to the specified options. */
214 int quote,
215 int output_tabs,
216 int numbers,
217 int numbers_at_empty_lines,
218 int mark_line_ends,
219 int squeeze_empty_lines)
221 /* Last character read from the input buffer. */
222 unsigned char ch;
224 /* Pointer to the next character in the input buffer. */
225 char *bpin;
227 /* Pointer to the first non-valid byte in the input buffer, i.e. the
228 current end of the buffer. */
229 char *eob;
231 /* Pointer to the position where the next character shall be written. */
232 char *bpout;
234 /* Number of characters read by the last read call. */
235 size_t n_read;
237 /* Determines how many consecutive newlines there have been in the
238 input. 0 newlines makes NEWLINES -1, 1 newline makes NEWLINES 1,
239 etc. Initially 0 to indicate that we are at the beginning of a
240 new line. The "state" of the procedure is determined by
241 NEWLINES. */
242 int newlines = newlines2;
244 #ifdef FIONREAD
245 /* If nonzero, use the FIONREAD ioctl, as an optimization.
246 (On Ultrix, it is not supported on NFS filesystems.) */
247 int use_fionread = 1;
248 #endif
250 /* The inbuf pointers are initialized so that BPIN > EOB, and thereby input
251 is read immediately. */
253 eob = inbuf;
254 bpin = eob + 1;
256 bpout = outbuf;
258 for (;;)
262 /* Write if there are at least OUTSIZE bytes in OUTBUF. */
264 if (outbuf + outsize <= bpout)
266 char *wp = outbuf;
267 size_t remaining_bytes;
270 if (full_write (STDOUT_FILENO, wp, outsize) != outsize)
271 error (EXIT_FAILURE, errno, _("write error"));
272 wp += outsize;
273 remaining_bytes = bpout - wp;
275 while (outsize <= remaining_bytes);
277 /* Move the remaining bytes to the beginning of the
278 buffer. */
280 memmove (outbuf, wp, remaining_bytes);
281 bpout = outbuf + remaining_bytes;
284 /* Is INBUF empty? */
286 if (bpin > eob)
288 #ifdef FIONREAD
289 int n_to_read = 0;
291 /* Is there any input to read immediately?
292 If not, we are about to wait,
293 so write all buffered output before waiting. */
295 if (use_fionread
296 && ioctl (input_desc, FIONREAD, &n_to_read) < 0)
298 /* Ultrix returns EOPNOTSUPP on NFS;
299 HP-UX returns ENOTTY on pipes.
300 SunOS returns EINVAL and
301 More/BSD returns ENODEV on special files
302 like /dev/null.
303 Irix-5 returns ENOSYS on pipes. */
304 if (errno == EOPNOTSUPP || errno == ENOTTY
305 || errno == EINVAL || errno == ENODEV
306 || errno == ENOSYS)
307 use_fionread = 0;
308 else
310 error (0, errno, _("cannot do ioctl on `%s'"), infile);
311 exit_status = 1;
312 newlines2 = newlines;
313 return;
316 if (n_to_read == 0)
317 #endif
319 size_t n_write = bpout - outbuf;
321 if (full_write (STDOUT_FILENO, outbuf, n_write) != n_write)
322 error (EXIT_FAILURE, errno, _("write error"));
323 bpout = outbuf;
326 /* Read more input into INBUF. */
328 n_read = safe_read (input_desc, inbuf, insize);
329 if (n_read == SAFE_READ_ERROR)
331 error (0, errno, "%s", infile);
332 exit_status = 1;
333 newlines2 = newlines;
334 return;
336 if (n_read == 0)
338 newlines2 = newlines;
339 return;
342 /* Update the pointers and insert a sentinel at the buffer
343 end. */
345 bpin = inbuf;
346 eob = bpin + n_read;
347 *eob = '\n';
349 else
351 /* It was a real (not a sentinel) newline. */
353 /* Was the last line empty?
354 (i.e. have two or more consecutive newlines been read?) */
356 if (++newlines > 0)
358 if (newlines >= 2)
360 /* Limit this to 2 here. Otherwise, with lots of
361 consecutive newlines, the counter could wrap
362 around at INT_MAX. */
363 newlines = 2;
365 /* Are multiple adjacent empty lines to be substituted
366 by single ditto (-s), and this was the second empty
367 line? */
368 if (squeeze_empty_lines)
370 ch = *bpin++;
371 continue;
375 /* Are line numbers to be written at empty lines (-n)? */
377 if (numbers && numbers_at_empty_lines)
379 next_line_num ();
380 bpout = stpcpy (bpout, line_num_print);
384 /* Output a currency symbol if requested (-e). */
386 if (mark_line_ends)
387 *bpout++ = '$';
389 /* Output the newline. */
391 *bpout++ = '\n';
393 ch = *bpin++;
395 while (ch == '\n');
397 /* Are we at the beginning of a line, and line numbers are requested? */
399 if (newlines >= 0 && numbers)
401 next_line_num ();
402 bpout = stpcpy (bpout, line_num_print);
405 /* Here CH cannot contain a newline character. */
407 /* The loops below continue until a newline character is found,
408 which means that the buffer is empty or that a proper newline
409 has been found. */
411 /* If quoting, i.e. at least one of -v, -e, or -t specified,
412 scan for chars that need conversion. */
413 if (quote)
415 for (;;)
417 if (ch >= 32)
419 if (ch < 127)
420 *bpout++ = ch;
421 else if (ch == 127)
423 *bpout++ = '^';
424 *bpout++ = '?';
426 else
428 *bpout++ = 'M';
429 *bpout++ = '-';
430 if (ch >= 128 + 32)
432 if (ch < 128 + 127)
433 *bpout++ = ch - 128;
434 else
436 *bpout++ = '^';
437 *bpout++ = '?';
440 else
442 *bpout++ = '^';
443 *bpout++ = ch - 128 + 64;
447 else if (ch == '\t' && output_tabs)
448 *bpout++ = '\t';
449 else if (ch == '\n')
451 newlines = -1;
452 break;
454 else
456 *bpout++ = '^';
457 *bpout++ = ch + 64;
460 ch = *bpin++;
463 else
465 /* Not quoting, neither of -v, -e, or -t specified. */
466 for (;;)
468 if (ch == '\t' && !output_tabs)
470 *bpout++ = '^';
471 *bpout++ = ch + 64;
473 else if (ch != '\n')
474 *bpout++ = ch;
475 else
477 newlines = -1;
478 break;
481 ch = *bpin++;
487 /* This is gross, but necessary, because of the way close_stdout
488 works and because this program closes STDOUT_FILENO directly. */
489 static void (*closeout_func) (void) = close_stdout;
491 static void
492 close_stdout_wrapper (void)
494 if (closeout_func)
495 (*closeout_func) ();
499 main (int argc, char **argv)
501 /* Optimal size of i/o operations of output. */
502 size_t outsize;
504 /* Optimal size of i/o operations of input. */
505 size_t insize;
507 /* Pointer to the input buffer. */
508 char *inbuf;
510 /* Pointer to the output buffer. */
511 char *outbuf;
513 int c;
515 /* Index in argv to processed argument. */
516 int argind;
518 /* Device number of the output (file or whatever). */
519 dev_t out_dev;
521 /* I-node number of the output. */
522 ino_t out_ino;
524 /* Nonzero if the output file should not be the same as any input file. */
525 int check_redirection = 1;
527 /* Nonzero if we have ever read standard input. */
528 int have_read_stdin = 0;
530 struct stat stat_buf;
532 /* Variables that are set according to the specified options. */
533 int numbers = 0;
534 int numbers_at_empty_lines = 1;
535 int squeeze_empty_lines = 0;
536 int mark_line_ends = 0;
537 int quote = 0;
538 int output_tabs = 1;
539 #if O_BINARY
540 int binary_files = 0;
541 int binary_output = 0;
542 #endif
543 int file_open_mode = O_RDONLY;
545 /* If nonzero, call cat, otherwise call simple_cat to do the actual work. */
546 int options = 0;
548 static struct option const long_options[] =
550 {"number-nonblank", no_argument, NULL, 'b'},
551 {"number", no_argument, NULL, 'n'},
552 {"squeeze-blank", no_argument, NULL, 's'},
553 {"show-nonprinting", no_argument, NULL, 'v'},
554 {"show-ends", no_argument, NULL, 'E'},
555 {"show-tabs", no_argument, NULL, 'T'},
556 {"show-all", no_argument, NULL, 'A'},
557 #if O_BINARY
558 {"binary", no_argument, NULL, 'B'},
559 #endif
560 {GETOPT_HELP_OPTION_DECL},
561 {GETOPT_VERSION_OPTION_DECL},
562 {NULL, 0, NULL, 0}
565 initialize_main (&argc, &argv);
566 program_name = argv[0];
567 setlocale (LC_ALL, "");
568 bindtextdomain (PACKAGE, LOCALEDIR);
569 textdomain (PACKAGE);
571 /* Arrange to close stdout if we exit via the
572 case_GETOPT_HELP_CHAR or case_GETOPT_VERSION_CHAR code. */
573 atexit (close_stdout_wrapper);
575 /* Parse command line options. */
577 while ((c = getopt_long (argc, argv,
578 #if O_BINARY
579 "benstuvABET"
580 #else
581 "benstuvAET"
582 #endif
583 , long_options, NULL)) != -1)
585 switch (c)
587 case 0:
588 break;
590 case 'b':
591 ++options;
592 numbers = 1;
593 numbers_at_empty_lines = 0;
594 break;
596 case 'e':
597 ++options;
598 mark_line_ends = 1;
599 quote = 1;
600 break;
602 case 'n':
603 ++options;
604 numbers = 1;
605 break;
607 case 's':
608 ++options;
609 squeeze_empty_lines = 1;
610 break;
612 case 't':
613 ++options;
614 output_tabs = 0;
615 quote = 1;
616 break;
618 case 'u':
619 /* We provide the -u feature unconditionally. */
620 break;
622 case 'v':
623 ++options;
624 quote = 1;
625 break;
627 case 'A':
628 ++options;
629 quote = 1;
630 mark_line_ends = 1;
631 output_tabs = 0;
632 break;
634 #if O_BINARY
635 case 'B':
636 ++options;
637 binary_files = 1;
638 break;
639 #endif
641 case 'E':
642 ++options;
643 mark_line_ends = 1;
644 break;
646 case 'T':
647 ++options;
648 output_tabs = 0;
649 break;
651 case_GETOPT_HELP_CHAR;
653 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
655 default:
656 usage (EXIT_FAILURE);
660 /* Don't close stdout on exit from here on. */
661 closeout_func = NULL;
663 /* Get device, i-node number, and optimal blocksize of output. */
665 if (fstat (STDOUT_FILENO, &stat_buf) < 0)
666 error (EXIT_FAILURE, errno, _("standard output"));
668 outsize = ST_BLKSIZE (stat_buf);
669 /* Input file can be output file for non-regular files.
670 fstat on pipes returns S_IFSOCK on some systems, S_IFIFO
671 on others, so the checking should not be done for those types,
672 and to allow things like cat < /dev/tty > /dev/tty, checking
673 is not done for device files either. */
675 if (S_ISREG (stat_buf.st_mode))
677 out_dev = stat_buf.st_dev;
678 out_ino = stat_buf.st_ino;
680 else
682 check_redirection = 0;
683 #ifdef lint /* Suppress `used before initialized' warning. */
684 out_dev = 0;
685 out_ino = 0;
686 #endif
689 #if O_BINARY
690 /* We always read and write in BINARY mode, since this is the
691 best way to copy the files verbatim. Exceptions are when
692 they request line numbering, squeezing of empty lines or
693 marking lines' ends: then we use text I/O, because otherwise
694 -b, -s and -E would surprise users on DOS/Windows where a line
695 with only CR-LF is an empty line. (Besides, if they ask for
696 one of these options, they don't care much about the original
697 file contents anyway). */
698 if ((!isatty (STDOUT_FILENO)
699 && !(numbers || squeeze_empty_lines || mark_line_ends))
700 || binary_files)
702 /* Switch stdout to BINARY mode. */
703 binary_output = 1;
704 SET_BINARY (STDOUT_FILENO);
705 /* When stdout is in binary mode, make sure all input files are
706 also read in binary mode. */
707 file_open_mode |= O_BINARY;
709 else if (quote)
711 /* If they want to see the non-printables, let's show them
712 those CR characters as well, so make the input binary.
713 But keep console output in text mode, so that LF causes
714 both CR and LF on output, and the output is readable. */
715 file_open_mode |= O_BINARY;
716 SET_BINARY (0);
718 /* Setting stdin to binary switches the console device to
719 raw I/O, which also affects stdout to console. Undo that. */
720 if (isatty (STDOUT_FILENO))
721 setmode (STDOUT_FILENO, O_TEXT);
723 #endif
725 /* Check if any of the input files are the same as the output file. */
727 /* Main loop. */
729 infile = "-";
730 argind = optind;
734 if (argind < argc)
735 infile = argv[argind];
737 if (infile[0] == '-' && infile[1] == 0)
739 have_read_stdin = 1;
740 input_desc = 0;
742 #if O_BINARY
743 /* Switch stdin to BINARY mode if needed. */
744 if (binary_output)
746 int tty_in = isatty (input_desc);
748 /* If stdin is a terminal device, and it is the ONLY
749 input file (i.e. we didn't write anything to the
750 output yet), switch the output back to TEXT mode.
751 This is so "cat > xyzzy" creates a DOS-style text
752 file, like people expect. */
753 if (tty_in && optind <= argc)
754 setmode (STDOUT_FILENO, O_TEXT);
755 else
757 SET_BINARY (input_desc);
758 # ifdef __DJGPP__
759 /* This is DJGPP-specific. By default, switching console
760 to binary mode disables SIGINT. But we want terminal
761 reads to be interruptible. */
762 if (tty_in)
763 __djgpp_set_ctrl_c (1);
764 # endif
767 #endif
769 else
771 input_desc = open (infile, file_open_mode);
772 if (input_desc < 0)
774 error (0, errno, "%s", infile);
775 exit_status = 1;
776 continue;
780 if (fstat (input_desc, &stat_buf) < 0)
782 error (0, errno, "%s", infile);
783 exit_status = 1;
784 goto contin;
786 insize = ST_BLKSIZE (stat_buf);
788 /* Compare the device and i-node numbers of this input file with
789 the corresponding values of the (output file associated with)
790 stdout, and skip this input file if they coincide. Input
791 files cannot be redirected to themselves. */
793 if (check_redirection
794 && stat_buf.st_dev == out_dev && stat_buf.st_ino == out_ino
795 && (input_desc != STDIN_FILENO))
797 error (0, 0, _("%s: input file is output file"), infile);
798 exit_status = 1;
799 goto contin;
802 /* Select which version of `cat' to use. If any options (more than -u,
803 --version, or --help) were specified, use `cat', otherwise use
804 `simple_cat'. */
806 if (options == 0)
808 insize = max (insize, outsize);
809 inbuf = xmalloc (insize);
811 simple_cat (inbuf, insize);
813 else
815 inbuf = xmalloc (insize + 1);
817 /* Why are (OUTSIZE - 1 + INSIZE * 4 + LINE_COUNTER_BUF_LEN)
818 bytes allocated for the output buffer?
820 A test whether output needs to be written is done when the input
821 buffer empties or when a newline appears in the input. After
822 output is written, at most (OUTSIZE - 1) bytes will remain in the
823 buffer. Now INSIZE bytes of input is read. Each input character
824 may grow by a factor of 4 (by the prepending of M-^). If all
825 characters do, and no newlines appear in this block of input, we
826 will have at most (OUTSIZE - 1 + INSIZE * 4) bytes in the buffer.
827 If the last character in the preceding block of input was a
828 newline, a line number may be written (according to the given
829 options) as the first thing in the output buffer. (Done after the
830 new input is read, but before processing of the input begins.)
831 A line number requires seldom more than LINE_COUNTER_BUF_LEN
832 positions. */
834 outbuf = xmalloc (outsize - 1 + insize * 4 + LINE_COUNTER_BUF_LEN);
836 cat (inbuf, insize, outbuf, outsize, quote,
837 output_tabs, numbers, numbers_at_empty_lines, mark_line_ends,
838 squeeze_empty_lines);
840 free (outbuf);
843 free (inbuf);
845 contin:
846 if (!STREQ (infile, "-") && close (input_desc) < 0)
848 error (0, errno, "%s", infile);
849 exit_status = 1;
852 while (++argind < argc);
854 if (have_read_stdin && close (STDIN_FILENO) < 0)
855 error (EXIT_FAILURE, errno, _("closing standard input"));
857 if (close (STDOUT_FILENO) < 0)
858 error (EXIT_FAILURE, errno, _("closing standard output"));
860 exit (exit_status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);