1 /* cat -- concatenate files and print on the standard output.
2 Copyright (C) 88, 90, 91, 1995-2001 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>
36 #include "full-write.h"
37 #include "safe-read.h"
39 /* The official name of this program (e.g., no `g' prefix). */
40 #define PROGRAM_NAME "cat"
42 #define AUTHORS N_ ("Torbjorn Granlund and Richard M. Stallman")
44 /* Undefine, to avoid warning about redefinition on some systems. */
46 #define max(h,i) ((h) > (i) ? (h) : (i))
48 /* Name under which this program was invoked. */
51 /* Name of input file. May be "-". */
54 /* Descriptor on which input file is open. */
55 static int input_desc;
57 /* Buffer for line numbers.
58 An 11 digit counter may overflow within an hour on a P2/466,
59 an 18 digit counter needs about 1000y */
60 #define LINE_COUNTER_BUF_LEN 20
61 static char line_buf[LINE_COUNTER_BUF_LEN] =
63 ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
64 ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '0',
68 /* Position in `line_buf' where printing starts. This will not change
69 unless the number of lines is larger than 999999. */
70 static char *line_num_print = line_buf + LINE_COUNTER_BUF_LEN - 8;
72 /* Position of the first digit in `line_buf'. */
73 static char *line_num_start = line_buf + LINE_COUNTER_BUF_LEN - 3;
75 /* Position of the last digit in `line_buf'. */
76 static char *line_num_end = line_buf + LINE_COUNTER_BUF_LEN - 3;
78 /* Preserves the `cat' function's local `newlines' between invocations. */
79 static int newlines2 = 0;
81 /* Count of non-fatal error conditions. */
82 static int exit_status = 0;
88 fprintf (stderr, _("Try `%s --help' for more information.\n"),
93 Usage: %s [OPTION] [FILE]...\n\
97 Concatenate FILE(s), or standard input, to standard output.\n\
99 -A, --show-all equivalent to -vET\n\
100 -b, --number-nonblank number nonblank 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 never more than one single blank line\n\
107 -t equivalent to -vT\n\
108 -T, --show-tabs display TAB characters as ^I\n\
110 -v, --show-nonprinting use ^ and M- notation, except for LFD and TAB\n\
111 --help display this help and exit\n\
112 --version output version information and exit\n\
114 With no FILE, or when FILE is -, read standard input.\n\
119 -B, --binary use binary writes to the console device.\n\n\
122 puts (_("\nReport bugs to <bug-textutils@gnu.org>."));
124 exit (status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
127 /* Compute the next line number. */
132 char *endp = line_num_end;
139 while (endp >= line_num_start);
140 if (line_num_start > line_buf)
141 *--line_num_start = '1';
144 if (line_num_start < line_num_print)
148 /* Plain cat. Copies the file behind `input_desc' to STDOUT_FILENO. */
152 /* Pointer to the buffer, used by reads and writes. */
155 /* Number of characters preferably read or written by each read and write
159 /* Actual number of characters read, and therefore written. */
162 /* Loop until the end of the file. */
166 /* Read a block of input. */
168 n_read = safe_read (input_desc, buf, bufsize);
171 error (0, errno, "%s", infile);
176 /* End of this file? */
181 /* Write this block out. */
183 if (full_write (STDOUT_FILENO, buf, n_read) != n_read)
184 error (EXIT_FAILURE, errno, _("write error"));
188 /* Cat the file behind INPUT_DESC to the file behind OUTPUT_DESC.
189 Called if any option more than -u was specified.
191 A newline character is always put at the end of the buffer, to make
192 an explicit test for buffer end unnecessary. */
196 /* Pointer to the beginning of the input buffer. */
197 unsigned char *inbuf,
199 /* Number of characters read in each read call. */
202 /* Pointer to the beginning of the output buffer. */
203 unsigned char *outbuf,
205 /* Number of characters written by each write call. */
208 /* Variables that have values according to the specified options. */
212 int numbers_at_empty_lines,
214 int squeeze_empty_lines)
216 /* Last character read from the input buffer. */
219 /* Pointer to the next character in the input buffer. */
222 /* Pointer to the first non-valid byte in the input buffer, i.e. the
223 current end of the buffer. */
226 /* Pointer to the position where the next character shall be written. */
227 unsigned char *bpout;
229 /* Number of characters read by the last read call. */
232 /* Determines how many consecutive newlines there have been in the
233 input. 0 newlines makes NEWLINES -1, 1 newline makes NEWLINES 1,
234 etc. Initially 0 to indicate that we are at the beginning of a
235 new line. The "state" of the procedure is determined by
237 int newlines = newlines2;
240 /* If nonzero, use the FIONREAD ioctl, as an optimization.
241 (On Ultrix, it is not supported on NFS filesystems.) */
242 int use_fionread = 1;
245 /* The inbuf pointers are initialized so that BPIN > EOB, and thereby input
246 is read immediately. */
257 /* Write if there are at least OUTSIZE bytes in OUTBUF. */
259 if (bpout - outbuf >= outsize)
261 unsigned char *wp = outbuf;
264 if (full_write (STDOUT_FILENO, wp, outsize) < 0)
265 error (EXIT_FAILURE, errno, _("write error"));
268 while (bpout - wp >= outsize);
270 /* Move the remaining bytes to the beginning of the
273 memmove (outbuf, wp, bpout - wp);
274 bpout = outbuf + (bpout - wp);
277 /* Is INBUF empty? */
284 /* Is there any input to read immediately?
285 If not, we are about to wait,
286 so write all buffered output before waiting. */
289 && ioctl (input_desc, FIONREAD, &n_to_read) < 0)
291 /* Ultrix returns EOPNOTSUPP on NFS;
292 HP-UX returns ENOTTY on pipes.
293 SunOS returns EINVAL and
294 More/BSD returns ENODEV on special files
296 Irix-5 returns ENOSYS on pipes. */
297 if (errno == EOPNOTSUPP || errno == ENOTTY
298 || errno == EINVAL || errno == ENODEV
306 error (0, errno, _("cannot do ioctl on `%s'"), infile);
308 newlines2 = newlines;
315 int n_write = bpout - outbuf;
317 if (full_write (STDOUT_FILENO, outbuf, n_write) < 0)
318 error (EXIT_FAILURE, errno, _("write error"));
322 /* Read more input into INBUF. */
324 n_read = safe_read (input_desc, inbuf, insize);
327 error (0, errno, "%s", infile);
329 newlines2 = newlines;
334 newlines2 = newlines;
338 /* Update the pointers and insert a sentinel at the buffer
347 /* It was a real (not a sentinel) newline. */
349 /* Was the last line empty?
350 (i.e. have two or more consecutive newlines been read?) */
356 /* Limit this to 2 here. Otherwise, with lots of
357 consecutive newlines, the counter could wrap
358 around at INT_MAX. */
361 /* Are multiple adjacent empty lines to be substituted
362 by single ditto (-s), and this was the second empty
364 if (squeeze_empty_lines)
371 /* Are line numbers to be written at empty lines (-n)? */
373 if (numbers && numbers_at_empty_lines)
376 bpout = (unsigned char *) stpcpy ((char *) bpout,
381 /* Output a currency symbol if requested (-e). */
386 /* Output the newline. */
394 /* Are we at the beginning of a line, and line numbers are requested? */
396 if (newlines >= 0 && numbers)
399 bpout = (unsigned char *) stpcpy ((char *) bpout, line_num_print);
402 /* Here CH cannot contain a newline character. */
404 /* The loops below continue until a newline character is found,
405 which means that the buffer is empty or that a proper newline
408 /* If quoting, i.e. at least one of -v, -e, or -t specified,
409 scan for chars that need conversion. */
440 *bpout++ = ch - 128 + 64;
444 else if (ch == '\t' && output_tabs)
462 /* Not quoting, neither of -v, -e, or -t specified. */
465 if (ch == '\t' && !output_tabs)
485 main (int argc, char **argv)
487 /* Optimal size of i/o operations of output. */
490 /* Optimal size of i/o operations of input. */
493 /* Pointer to the input buffer. */
494 unsigned char *inbuf;
496 /* Pointer to the output buffer. */
497 unsigned char *outbuf;
501 /* Index in argv to processed argument. */
504 /* Device number of the output (file or whatever). */
507 /* I-node number of the output. */
510 /* Nonzero if the output file should not be the same as any input file. */
511 int check_redirection = 1;
513 /* Nonzero if we have ever read standard input. */
514 int have_read_stdin = 0;
516 struct stat stat_buf;
518 /* Variables that are set according to the specified options. */
520 int numbers_at_empty_lines = 1;
521 int squeeze_empty_lines = 0;
522 int mark_line_ends = 0;
526 int binary_files = 0;
527 int binary_output = 0;
529 int file_open_mode = O_RDONLY;
531 /* If nonzero, call cat, otherwise call simple_cat to do the actual work. */
534 static struct option const long_options[] =
536 {"number-nonblank", no_argument, NULL, 'b'},
537 {"number", no_argument, NULL, 'n'},
538 {"squeeze-blank", no_argument, NULL, 's'},
539 {"show-nonprinting", no_argument, NULL, 'v'},
540 {"show-ends", no_argument, NULL, 'E'},
541 {"show-tabs", no_argument, NULL, 'T'},
542 {"show-all", no_argument, NULL, 'A'},
544 {"binary", no_argument, NULL, 'B'},
546 {GETOPT_HELP_OPTION_DECL},
547 {GETOPT_VERSION_OPTION_DECL},
551 program_name = argv[0];
552 setlocale (LC_ALL, "");
553 bindtextdomain (PACKAGE, LOCALEDIR);
554 textdomain (PACKAGE);
556 atexit (close_stdout);
558 /* Parse command line options. */
560 while ((c = getopt_long (argc, argv,
566 , long_options, NULL)) != -1)
576 numbers_at_empty_lines = 0;
592 squeeze_empty_lines = 1;
602 /* We provide the -u feature unconditionally. */
634 case_GETOPT_HELP_CHAR;
636 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
639 usage (EXIT_FAILURE);
643 /* Get device, i-node number, and optimal blocksize of output. */
645 if (fstat (STDOUT_FILENO, &stat_buf) < 0)
646 error (EXIT_FAILURE, errno, _("standard output"));
648 outsize = ST_BLKSIZE (stat_buf);
649 /* Input file can be output file for non-regular files.
650 fstat on pipes returns S_IFSOCK on some systems, S_IFIFO
651 on others, so the checking should not be done for those types,
652 and to allow things like cat < /dev/tty > /dev/tty, checking
653 is not done for device files either. */
655 if (S_ISREG (stat_buf.st_mode))
657 out_dev = stat_buf.st_dev;
658 out_ino = stat_buf.st_ino;
662 check_redirection = 0;
663 #ifdef lint /* Suppress `used before initialized' warning. */
670 /* We always read and write in BINARY mode, since this is the
671 best way to copy the files verbatim. Exceptions are when
672 they request line numbering, squeezing of empty lines or
673 marking lines' ends: then we use text I/O, because otherwise
674 -b, -s and -E would surprise users on DOS/Windows where a line
675 with only CR-LF is an empty line. (Besides, if they ask for
676 one of these options, they don't care much about the original
677 file contents anyway). */
678 if ((!isatty (STDOUT_FILENO)
679 && !(numbers || squeeze_empty_lines || mark_line_ends))
682 /* Switch stdout to BINARY mode. */
684 SET_BINARY (STDOUT_FILENO);
685 /* When stdout is in binary mode, make sure all input files are
686 also read in binary mode. */
687 file_open_mode |= O_BINARY;
691 /* If they want to see the non-printables, let's show them
692 those CR characters as well, so make the input binary.
693 But keep console output in text mode, so that LF causes
694 both CR and LF on output, and the output is readable. */
695 file_open_mode |= O_BINARY;
698 /* Setting stdin to binary switches the console device to
699 raw I/O, which also affects stdout to console. Undo that. */
700 if (isatty (STDOUT_FILENO))
701 setmode (STDOUT_FILENO, O_TEXT);
705 /* Check if any of the input files are the same as the output file. */
715 infile = argv[argind];
717 if (infile[0] == '-' && infile[1] == 0)
723 /* Switch stdin to BINARY mode if needed. */
726 int tty_in = isatty (input_desc);
728 /* If stdin is a terminal device, and it is the ONLY
729 input file (i.e. we didn't write anything to the
730 output yet), switch the output back to TEXT mode.
731 This is so "cat > xyzzy" creates a DOS-style text
732 file, like people expect. */
733 if (tty_in && optind <= argc)
734 setmode (STDOUT_FILENO, O_TEXT);
737 SET_BINARY (input_desc);
739 /* This is DJGPP-specific. By default, switching console
740 to binary mode disables SIGINT. But we want terminal
741 reads to be interruptible. */
743 __djgpp_set_ctrl_c (1);
751 input_desc = open (infile, file_open_mode);
754 error (0, errno, "%s", infile);
760 if (fstat (input_desc, &stat_buf) < 0)
762 error (0, errno, "%s", infile);
766 insize = ST_BLKSIZE (stat_buf);
768 /* Compare the device and i-node numbers of this input file with
769 the corresponding values of the (output file associated with)
770 stdout, and skip this input file if they coincide. Input
771 files cannot be redirected to themselves. */
773 if (check_redirection
774 && stat_buf.st_dev == out_dev && stat_buf.st_ino == out_ino
775 && (input_desc != STDIN_FILENO))
777 error (0, 0, _("%s: input file is output file"), infile);
782 /* Select which version of `cat' to use. If any options (more than -u,
783 --version, or --help) were specified, use `cat', otherwise use
788 insize = max (insize, outsize);
789 inbuf = (unsigned char *) xmalloc (insize);
791 simple_cat (inbuf, insize);
795 inbuf = (unsigned char *) xmalloc (insize + 1);
797 /* Why are (OUTSIZE - 1 + INSIZE * 4 + LINE_COUNTER_BUF_LEN)
798 bytes allocated for the output buffer?
800 A test whether output needs to be written is done when the input
801 buffer empties or when a newline appears in the input. After
802 output is written, at most (OUTSIZE - 1) bytes will remain in the
803 buffer. Now INSIZE bytes of input is read. Each input character
804 may grow by a factor of 4 (by the prepending of M-^). If all
805 characters do, and no newlines appear in this block of input, we
806 will have at most (OUTSIZE - 1 + INSIZE * 4) bytes in the buffer.
807 If the last character in the preceding block of input was a
808 newline, a line number may be written (according to the given
809 options) as the first thing in the output buffer. (Done after the
810 new input is read, but before processing of the input begins.)
811 A line number requires seldom more than LINE_COUNTER_BUF_LEN
814 outbuf = (unsigned char *) xmalloc (outsize - 1 + insize * 4
815 + LINE_COUNTER_BUF_LEN);
817 cat (inbuf, insize, outbuf, outsize, quote,
818 output_tabs, numbers, numbers_at_empty_lines, mark_line_ends,
819 squeeze_empty_lines);
827 if (!STREQ (infile, "-") && close (input_desc) < 0)
829 error (0, errno, "%s", infile);
833 while (++argind < argc);
835 if (have_read_stdin && close (0) < 0)
836 error (EXIT_FAILURE, errno, "-");
838 exit (exit_status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);