1 /* cat -- concatenate files and print on the standard output.
2 Copyright (C) 88, 90, 91, 1995-2003 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 "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. */
45 #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 /* 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',
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 /* Count of non-fatal error conditions. */
81 static int exit_status = 0;
87 fprintf (stderr, _("Try `%s --help' for more information.\n"),
92 Usage: %s [OPTION] [FILE]...\n\
96 Concatenate FILE(s), or standard input, to standard output.\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\
106 -t equivalent to -vT\n\
107 -T, --show-tabs display TAB characters as ^I\n\
109 -v, --show-nonprinting use ^ and M- notation, except for LFD and TAB\n\
111 fputs (HELP_OPTION_DESCRIPTION, stdout);
112 fputs (VERSION_OPTION_DESCRIPTION, stdout);
115 With no FILE, or when FILE is -, read standard input.\n\
120 -B, --binary use binary writes to the console device.\n\n\
123 printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
125 exit (status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
128 /* Compute the next line number. */
133 char *endp = line_num_end;
140 while (endp >= line_num_start);
141 if (line_num_start > line_buf)
142 *--line_num_start = '1';
145 if (line_num_start < line_num_print)
149 /* Plain cat. Copies the file behind `input_desc' to STDOUT_FILENO. */
153 /* Pointer to the buffer, used by reads and writes. */
156 /* Number of characters preferably read or written by each read and write
160 /* Actual number of characters read, and therefore written. */
163 /* Loop until the end of the file. */
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);
177 /* End of this file? */
182 /* Write this block out. */
185 /* The following is ok, since we know that 0 < 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. */
201 /* Pointer to the beginning of the input buffer. */
204 /* Number of characters read in each read call. */
207 /* Pointer to the beginning of the output buffer. */
210 /* Number of characters written by each write call. */
213 /* Variables that have values according to the specified options. */
217 int numbers_at_empty_lines,
219 int squeeze_empty_lines)
221 /* Last character read from the input buffer. */
224 /* Pointer to the next character in the input buffer. */
227 /* Pointer to the first non-valid byte in the input buffer, i.e. the
228 current end of the buffer. */
231 /* Pointer to the position where the next character shall be written. */
234 /* Number of characters read by the last read call. */
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
242 int newlines = newlines2;
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;
250 /* The inbuf pointers are initialized so that BPIN > EOB, and thereby input
251 is read immediately. */
262 /* Write if there are at least OUTSIZE bytes in OUTBUF. */
264 if (outbuf + outsize <= bpout)
267 size_t remaining_bytes;
270 if (full_write (STDOUT_FILENO, wp, outsize) != outsize)
271 error (EXIT_FAILURE, errno, _("write error"));
273 remaining_bytes = bpout - wp;
275 while (outsize <= remaining_bytes);
277 /* Move the remaining bytes to the beginning of the
280 memmove (outbuf, wp, remaining_bytes);
281 bpout = outbuf + remaining_bytes;
284 /* Is INBUF empty? */
291 /* Is there any input to read immediately?
292 If not, we are about to wait,
293 so write all buffered output before waiting. */
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
303 Irix-5 returns ENOSYS on pipes. */
304 if (errno == EOPNOTSUPP || errno == ENOTTY
305 || errno == EINVAL || errno == ENODEV
310 error (0, errno, _("cannot do ioctl on `%s'"), infile);
312 newlines2 = newlines;
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"));
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);
333 newlines2 = newlines;
338 newlines2 = newlines;
342 /* Update the pointers and insert a sentinel at the buffer
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?) */
360 /* Limit this to 2 here. Otherwise, with lots of
361 consecutive newlines, the counter could wrap
362 around at INT_MAX. */
365 /* Are multiple adjacent empty lines to be substituted
366 by single ditto (-s), and this was the second empty
368 if (squeeze_empty_lines)
375 /* Are line numbers to be written at empty lines (-n)? */
377 if (numbers && numbers_at_empty_lines)
380 bpout = stpcpy (bpout, line_num_print);
384 /* Output a currency symbol if requested (-e). */
389 /* Output the newline. */
397 /* Are we at the beginning of a line, and line numbers are requested? */
399 if (newlines >= 0 && numbers)
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
411 /* If quoting, i.e. at least one of -v, -e, or -t specified,
412 scan for chars that need conversion. */
443 *bpout++ = ch - 128 + 64;
447 else if (ch == '\t' && output_tabs)
465 /* Not quoting, neither of -v, -e, or -t specified. */
468 if (ch == '\t' && !output_tabs)
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;
492 close_stdout_wrapper (void)
499 main (int argc, char **argv)
501 /* Optimal size of i/o operations of output. */
504 /* Optimal size of i/o operations of input. */
507 /* Pointer to the input buffer. */
510 /* Pointer to the output buffer. */
515 /* Index in argv to processed argument. */
518 /* Device number of the output (file or whatever). */
521 /* I-node number of the output. */
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. */
534 int numbers_at_empty_lines = 1;
535 int squeeze_empty_lines = 0;
536 int mark_line_ends = 0;
540 int binary_files = 0;
541 int binary_output = 0;
543 int file_open_mode = O_RDONLY;
545 /* If nonzero, call cat, otherwise call simple_cat to do the actual work. */
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'},
558 {"binary", no_argument, NULL, 'B'},
560 {GETOPT_HELP_OPTION_DECL},
561 {GETOPT_VERSION_OPTION_DECL},
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,
583 , long_options, NULL)) != -1)
593 numbers_at_empty_lines = 0;
609 squeeze_empty_lines = 1;
619 /* We provide the -u feature unconditionally. */
651 case_GETOPT_HELP_CHAR;
653 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
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;
682 check_redirection = 0;
683 #ifdef lint /* Suppress `used before initialized' warning. */
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))
702 /* Switch stdout to BINARY mode. */
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;
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;
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);
725 /* Check if any of the input files are the same as the output file. */
735 infile = argv[argind];
737 if (infile[0] == '-' && infile[1] == 0)
743 /* Switch stdin to BINARY mode if needed. */
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);
757 SET_BINARY (input_desc);
759 /* This is DJGPP-specific. By default, switching console
760 to binary mode disables SIGINT. But we want terminal
761 reads to be interruptible. */
763 __djgpp_set_ctrl_c (1);
771 input_desc = open (infile, file_open_mode);
774 error (0, errno, "%s", infile);
780 if (fstat (input_desc, &stat_buf) < 0)
782 error (0, errno, "%s", infile);
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);
802 /* Select which version of `cat' to use. If any options (more than -u,
803 --version, or --help) were specified, use `cat', otherwise use
808 insize = max (insize, outsize);
809 inbuf = xmalloc (insize);
811 simple_cat (inbuf, insize);
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
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);
846 if (!STREQ (infile, "-") && close (input_desc) < 0)
848 error (0, errno, "%s", infile);
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);