1 /* cat -- concatenate files and print on the standard output.
2 Copyright (C) 88, 90, 91, 1995-1999 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)
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. */
29 #include <sys/types.h>
31 # include <sys/ioctl.h>
35 #include "long-options.h"
36 #include "safe-read.h"
38 /* The official name of this program (e.g., no `g' prefix). */
39 #define PROGRAM_NAME "cat"
41 /* Undefine, to avoid warning about redefinition on some systems. */
43 #define max(h,i) ((h) > (i) ? (h) : (i))
47 /* Name under which this program was invoked. */
50 /* Name of input file. May be "-". */
53 /* Descriptor on which input file is open. */
54 static int input_desc;
56 /* Descriptor on which output file is open. Always is 1. */
57 static int output_desc;
59 /* Buffer for line numbers. */
60 static char line_buf[13] =
61 {' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '0', '\t', '\0'};
63 /* Position in `line_buf' where printing starts. This will not change
64 unless the number of lines is larger than 999999. */
65 static char *line_num_print = line_buf + 5;
67 /* Position of the first digit in `line_buf'. */
68 static char *line_num_start = line_buf + 10;
70 /* Position of the last digit in `line_buf'. */
71 static char *line_num_end = line_buf + 10;
73 /* Preserves the `cat' function's local `newlines' between invocations. */
74 static int newlines2 = 0;
76 /* Count of non-fatal error conditions. */
77 static int exit_status = 0;
83 fprintf (stderr, _("Try `%s --help' for more information.\n"),
88 Usage: %s [OPTION] [FILE]...\n\
92 Concatenate FILE(s), or standard input, to standard output.\n\
94 -A, --show-all equivalent to -vET\n\
95 -b, --number-nonblank number nonblank output lines\n\
96 -e equivalent to -vE\n\
97 -E, --show-ends display $ at end of each line\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 -T, --show-tabs display TAB characters as ^I\n\
103 -v, --show-nonprinting use ^ and M- notation, except for LFD and TAB\n\
104 --help display this help and exit\n\
105 --version output version information and exit\n\
107 With no FILE, or when FILE is -, read standard input.\n\
112 -B, --binary use binary writes to the console device.\n\n\
115 puts (_("\nReport bugs to <bug-textutils@gnu.org>."));
117 exit (status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
120 /* Compute the next line number. */
125 char *endp = line_num_end;
132 while (endp >= line_num_start);
133 *--line_num_start = '1';
134 if (line_num_start < line_num_print)
138 /* Plain cat. Copies the file behind `input_desc' to the file behind
143 /* Pointer to the buffer, used by reads and writes. */
146 /* Number of characters preferably read or written by each read and write
150 /* Actual number of characters read, and therefore written. */
153 /* Loop until the end of the file. */
157 /* Read a block of input. */
159 n_read = safe_read (input_desc, buf, bufsize);
162 error (0, errno, "%s", infile);
167 /* End of this file? */
172 /* Write this block out. */
174 if (full_write (output_desc, buf, n_read) < 0)
175 error (EXIT_FAILURE, errno, _("write error"));
179 /* Cat the file behind INPUT_DESC to the file behind OUTPUT_DESC.
180 Called if any option more than -u was specified.
182 A newline character is always put at the end of the buffer, to make
183 an explicit test for buffer end unnecessary. */
187 /* Pointer to the beginning of the input buffer. */
188 unsigned char *inbuf,
190 /* Number of characters read in each read call. */
193 /* Pointer to the beginning of the output buffer. */
194 unsigned char *outbuf,
196 /* Number of characters written by each write call. */
199 /* Variables that have values according to the specified options. */
203 int numbers_at_empty_lines,
205 int squeeze_empty_lines)
207 /* Last character read from the input buffer. */
210 /* Pointer to the next character in the input buffer. */
213 /* Pointer to the first non-valid byte in the input buffer, i.e. the
214 current end of the buffer. */
217 /* Pointer to the position where the next character shall be written. */
218 unsigned char *bpout;
220 /* Number of characters read by the last read call. */
223 /* Determines how many consecutive newlines there have been in the
224 input. 0 newlines makes NEWLINES -1, 1 newline makes NEWLINES 1,
225 etc. Initially 0 to indicate that we are at the beginning of a
226 new line. The "state" of the procedure is determined by
228 int newlines = newlines2;
231 /* If nonzero, use the FIONREAD ioctl, as an optimization.
232 (On Ultrix, it is not supported on NFS filesystems.) */
233 int use_fionread = 1;
236 /* The inbuf pointers are initialized so that BPIN > EOB, and thereby input
237 is read immediately. */
248 /* Write if there are at least OUTSIZE bytes in OUTBUF. */
250 if (bpout - outbuf >= outsize)
252 unsigned char *wp = outbuf;
255 if (full_write (output_desc, wp, outsize) < 0)
256 error (EXIT_FAILURE, errno, _("write error"));
259 while (bpout - wp >= outsize);
261 /* Move the remaining bytes to the beginning of the
264 memmove (outbuf, wp, bpout - wp);
265 bpout = outbuf + (bpout - wp);
268 /* Is INBUF empty? */
275 /* Is there any input to read immediately?
276 If not, we are about to wait,
277 so write all buffered output before waiting. */
280 && ioctl (input_desc, FIONREAD, &n_to_read) < 0)
282 /* Ultrix returns EOPNOTSUPP on NFS;
283 HP-UX returns ENOTTY on pipes.
284 SunOS returns EINVAL and
285 More/BSD returns ENODEV on special files
287 Irix-5 returns ENOSYS on pipes. */
288 if (errno == EOPNOTSUPP || errno == ENOTTY
289 || errno == EINVAL || errno == ENODEV
297 error (0, errno, _("cannot do ioctl on `%s'"), infile);
299 newlines2 = newlines;
306 int n_write = bpout - outbuf;
308 if (full_write (output_desc, outbuf, n_write) < 0)
309 error (EXIT_FAILURE, errno, _("write error"));
313 /* Read more input into INBUF. */
315 n_read = safe_read (input_desc, inbuf, insize);
318 error (0, errno, "%s", infile);
320 newlines2 = newlines;
325 newlines2 = newlines;
329 /* Update the pointers and insert a sentinel at the buffer
338 /* It was a real (not a sentinel) newline. */
340 /* Was the last line empty?
341 (i.e. have two or more consecutive newlines been read?) */
345 /* Are multiple adjacent empty lines to be substituted by
346 single ditto (-s), and this was the second empty line? */
348 if (squeeze_empty_lines && newlines >= 2)
354 /* Are line numbers to be written at empty lines (-n)? */
356 if (numbers && numbers_at_empty_lines)
359 bpout = (unsigned char *) stpcpy ((char *) bpout,
364 /* Output a currency symbol if requested (-e). */
369 /* Output the newline. */
377 /* Are we at the beginning of a line, and line numbers are requested? */
379 if (newlines >= 0 && numbers)
382 bpout = (unsigned char *) stpcpy ((char *) bpout, line_num_print);
385 /* Here CH cannot contain a newline character. */
387 /* The loops below continue until a newline character is found,
388 which means that the buffer is empty or that a proper newline
391 /* If quoting, i.e. at least one of -v, -e, or -t specified,
392 scan for chars that need conversion. */
423 *bpout++ = ch - 128 + 64;
427 else if (ch == '\t' && output_tabs)
445 /* Not quoting, neither of -v, -e, or -t specified. */
448 if (ch == '\t' && !output_tabs)
468 main (int argc, char **argv)
470 /* Optimal size of i/o operations of output. */
473 /* Optimal size of i/o operations of input. */
476 /* Pointer to the input buffer. */
477 unsigned char *inbuf;
479 /* Pointer to the output buffer. */
480 unsigned char *outbuf;
484 /* Index in argv to processed argument. */
487 /* Device number of the output (file or whatever). */
490 /* I-node number of the output. */
493 /* Nonzero if the output file should not be the same as any input file. */
494 int check_redirection = 1;
496 /* Nonzero if we have ever read standard input. */
497 int have_read_stdin = 0;
499 struct stat stat_buf;
501 /* Variables that are set according to the specified options. */
503 int numbers_at_empty_lines = 1;
504 int squeeze_empty_lines = 0;
505 int mark_line_ends = 0;
509 int binary_files = 0;
510 int binary_output = 0;
512 int file_open_mode = O_RDONLY;
514 /* If nonzero, call cat, otherwise call simple_cat to do the actual work. */
517 static struct option const long_options[] =
519 {"number-nonblank", no_argument, NULL, 'b'},
520 {"number", no_argument, NULL, 'n'},
521 {"squeeze-blank", no_argument, NULL, 's'},
522 {"show-nonprinting", no_argument, NULL, 'v'},
523 {"show-ends", no_argument, NULL, 'E'},
524 {"show-tabs", no_argument, NULL, 'T'},
525 {"show-all", no_argument, NULL, 'A'},
527 {"binary", no_argument, NULL, 'B'},
532 program_name = argv[0];
533 setlocale (LC_ALL, "");
534 bindtextdomain (PACKAGE, LOCALEDIR);
535 textdomain (PACKAGE);
537 parse_long_options (argc, argv, "cat", GNU_PACKAGE, VERSION,
538 "Torbjorn Granlund and Richard M. Stallman", usage);
540 /* Parse command line options. */
542 while ((c = getopt_long (argc, argv,
548 , long_options, NULL)) != -1)
558 numbers_at_empty_lines = 0;
574 squeeze_empty_lines = 1;
584 /* We provide the -u feature unconditionally. */
617 usage (EXIT_FAILURE);
623 /* Get device, i-node number, and optimal blocksize of output. */
625 if (fstat (output_desc, &stat_buf) < 0)
626 error (EXIT_FAILURE, errno, _("standard output"));
628 outsize = ST_BLKSIZE (stat_buf);
629 /* Input file can be output file for non-regular files.
630 fstat on pipes returns S_IFSOCK on some systems, S_IFIFO
631 on others, so the checking should not be done for those types,
632 and to allow things like cat < /dev/tty > /dev/tty, checking
633 is not done for device files either. */
635 if (S_ISREG (stat_buf.st_mode))
637 out_dev = stat_buf.st_dev;
638 out_ino = stat_buf.st_ino;
642 check_redirection = 0;
643 #ifdef lint /* Suppress `used before initialized' warning. */
650 /* We always read and write in BINARY mode, since this is the
651 best way to copy the files verbatim. Exceptions are when
652 they request line numbering, squeezing of empty lines or
653 marking lines' ends: then we use text I/O, because otherwise
654 -b, -s and -E would surprise users on DOS/Windows where a line
655 with only CR-LF is an empty line. (Besides, if they ask for
656 one of these options, they don't care much about the original
657 file contents anyway). */
658 if ((!isatty (output_desc)
659 && !(numbers || squeeze_empty_lines || mark_line_ends))
662 /* Switch stdout to BINARY mode. */
664 SET_BINARY (output_desc);
668 /* If they want to see the non-printables, let's show them
669 those CR characters as well, so make the input binary.
670 But keep console output in text mode, so that LF causes
671 both CR and LF on output, and the output is readable. */
672 file_open_mode |= O_BINARY;
675 /* Setting stdin to binary switches the console device to
676 raw I/O, which also affects stdout to console. Undo that. */
677 if (isatty (output_desc))
678 setmode (output_desc, O_TEXT);
682 /* Check if any of the input files are the same as the output file. */
692 infile = argv[argind];
694 if (infile[0] == '-' && infile[1] == 0)
700 /* Switch stdin to BINARY mode if needed. */
703 int tty_in = isatty (input_desc);
705 /* If stdin is a terminal device, and it is the ONLY
706 input file (i.e. we didn't write anything to the
707 output yet), switch the output back to TEXT mode.
708 This is so "cat > xyzzy" creates a DOS-style text
709 file, like people expect. */
710 if (tty_in && optind <= argc)
711 setmode (output_desc, O_TEXT);
714 SET_BINARY (input_desc);
716 /* This is DJGPP-specific. By default, switching console
717 to binary mode disables SIGINT. But we want terminal
718 reads to be interruptible. */
720 __djgpp_set_ctrl_c (1);
728 input_desc = open (infile, file_open_mode);
731 error (0, errno, "%s", infile);
737 if (fstat (input_desc, &stat_buf) < 0)
739 error (0, errno, "%s", infile);
743 insize = ST_BLKSIZE (stat_buf);
745 /* Compare the device and i-node numbers of this input file with
746 the corresponding values of the (output file associated with)
747 stdout, and skip this input file if they coincide. Input
748 files cannot be redirected to themselves. */
750 if (check_redirection
751 && stat_buf.st_dev == out_dev && stat_buf.st_ino == out_ino
752 && (input_desc != STDIN_FILENO || output_desc != STDOUT_FILENO))
754 error (0, 0, _("%s: input file is output file"), infile);
759 /* Select which version of `cat' to use. If any options (more than -u,
760 --version, or --help) were specified, use `cat', otherwise use
765 insize = max (insize, outsize);
766 inbuf = (unsigned char *) xmalloc (insize);
768 simple_cat (inbuf, insize);
772 inbuf = (unsigned char *) xmalloc (insize + 1);
774 /* Why are (OUTSIZE - 1 + INSIZE * 4 + 13) bytes allocated for
777 A test whether output needs to be written is done when the input
778 buffer empties or when a newline appears in the input. After
779 output is written, at most (OUTSIZE - 1) bytes will remain in the
780 buffer. Now INSIZE bytes of input is read. Each input character
781 may grow by a factor of 4 (by the prepending of M-^). If all
782 characters do, and no newlines appear in this block of input, we
783 will have at most (OUTSIZE - 1 + INSIZE) bytes in the buffer. If
784 the last character in the preceding block of input was a
785 newline, a line number may be written (according to the given
786 options) as the first thing in the output buffer. (Done after the
787 new input is read, but before processing of the input begins.) A
788 line number requires seldom more than 13 positions. */
790 outbuf = (unsigned char *) xmalloc (outsize - 1 + insize * 4 + 13);
792 cat (inbuf, insize, outbuf, outsize, quote,
793 output_tabs, numbers, numbers_at_empty_lines, mark_line_ends,
794 squeeze_empty_lines);
802 if (!STREQ (infile, "-") && close (input_desc) < 0)
804 error (0, errno, "%s", infile);
808 while (++argind < argc);
810 if (have_read_stdin && close (0) < 0)
811 error (EXIT_FAILURE, errno, "-");
813 error (EXIT_FAILURE, errno, _("write error"));
815 exit (exit_status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);