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 "safe-read.h"
37 /* The official name of this program (e.g., no `g' prefix). */
38 #define PROGRAM_NAME "cat"
40 #define AUTHORS "Torbjorn Granlund and Richard M. Stallman"
42 /* Undefine, to avoid warning about redefinition on some systems. */
44 #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 /* Descriptor on which output file is open. Always is 1. */
58 static int output_desc
;
60 /* Buffer for line numbers. */
61 static char line_buf
[13] =
62 {' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '0', '\t', '\0'};
64 /* Position in `line_buf' where printing starts. This will not change
65 unless the number of lines is larger than 999999. */
66 static char *line_num_print
= line_buf
+ 5;
68 /* Position of the first digit in `line_buf'. */
69 static char *line_num_start
= line_buf
+ 10;
71 /* Position of the last digit in `line_buf'. */
72 static char *line_num_end
= line_buf
+ 10;
74 /* Preserves the `cat' function's local `newlines' between invocations. */
75 static int newlines2
= 0;
77 /* Count of non-fatal error conditions. */
78 static int exit_status
= 0;
84 fprintf (stderr
, _("Try `%s --help' for more information.\n"),
89 Usage: %s [OPTION] [FILE]...\n\
93 Concatenate FILE(s), or standard input, to standard output.\n\
95 -A, --show-all equivalent to -vET\n\
96 -b, --number-nonblank number nonblank output lines\n\
97 -e equivalent to -vE\n\
98 -E, --show-ends display $ at end of each line\n\
99 -n, --number number all output lines\n\
100 -s, --squeeze-blank never more than one single blank line\n\
101 -t equivalent to -vT\n\
102 -T, --show-tabs display TAB characters as ^I\n\
104 -v, --show-nonprinting use ^ and M- notation, except for LFD and TAB\n\
105 --help display this help and exit\n\
106 --version output version information and exit\n\
108 With no FILE, or when FILE is -, read standard input.\n\
113 -B, --binary use binary writes to the console device.\n\n\
116 puts (_("\nReport bugs to <bug-textutils@gnu.org>."));
118 exit (status
== 0 ? EXIT_SUCCESS
: EXIT_FAILURE
);
121 /* Compute the next line number. */
126 char *endp
= line_num_end
;
133 while (endp
>= line_num_start
);
134 *--line_num_start
= '1';
135 if (line_num_start
< line_num_print
)
139 /* Plain cat. Copies the file behind `input_desc' to the file behind
144 /* Pointer to the buffer, used by reads and writes. */
147 /* Number of characters preferably read or written by each read and write
151 /* Actual number of characters read, and therefore written. */
154 /* Loop until the end of the file. */
158 /* Read a block of input. */
160 n_read
= safe_read (input_desc
, buf
, bufsize
);
163 error (0, errno
, "%s", infile
);
168 /* End of this file? */
173 /* Write this block out. */
175 if (full_write (output_desc
, buf
, n_read
) < 0)
176 error (EXIT_FAILURE
, errno
, _("write error"));
180 /* Cat the file behind INPUT_DESC to the file behind OUTPUT_DESC.
181 Called if any option more than -u was specified.
183 A newline character is always put at the end of the buffer, to make
184 an explicit test for buffer end unnecessary. */
188 /* Pointer to the beginning of the input buffer. */
189 unsigned char *inbuf
,
191 /* Number of characters read in each read call. */
194 /* Pointer to the beginning of the output buffer. */
195 unsigned char *outbuf
,
197 /* Number of characters written by each write call. */
200 /* Variables that have values according to the specified options. */
204 int numbers_at_empty_lines
,
206 int squeeze_empty_lines
)
208 /* Last character read from the input buffer. */
211 /* Pointer to the next character in the input buffer. */
214 /* Pointer to the first non-valid byte in the input buffer, i.e. the
215 current end of the buffer. */
218 /* Pointer to the position where the next character shall be written. */
219 unsigned char *bpout
;
221 /* Number of characters read by the last read call. */
224 /* Determines how many consecutive newlines there have been in the
225 input. 0 newlines makes NEWLINES -1, 1 newline makes NEWLINES 1,
226 etc. Initially 0 to indicate that we are at the beginning of a
227 new line. The "state" of the procedure is determined by
229 int newlines
= newlines2
;
232 /* If nonzero, use the FIONREAD ioctl, as an optimization.
233 (On Ultrix, it is not supported on NFS filesystems.) */
234 int use_fionread
= 1;
237 /* The inbuf pointers are initialized so that BPIN > EOB, and thereby input
238 is read immediately. */
249 /* Write if there are at least OUTSIZE bytes in OUTBUF. */
251 if (bpout
- outbuf
>= outsize
)
253 unsigned char *wp
= outbuf
;
256 if (full_write (output_desc
, wp
, outsize
) < 0)
257 error (EXIT_FAILURE
, errno
, _("write error"));
260 while (bpout
- wp
>= outsize
);
262 /* Move the remaining bytes to the beginning of the
265 memmove (outbuf
, wp
, bpout
- wp
);
266 bpout
= outbuf
+ (bpout
- wp
);
269 /* Is INBUF empty? */
276 /* Is there any input to read immediately?
277 If not, we are about to wait,
278 so write all buffered output before waiting. */
281 && ioctl (input_desc
, FIONREAD
, &n_to_read
) < 0)
283 /* Ultrix returns EOPNOTSUPP on NFS;
284 HP-UX returns ENOTTY on pipes.
285 SunOS returns EINVAL and
286 More/BSD returns ENODEV on special files
288 Irix-5 returns ENOSYS on pipes. */
289 if (errno
== EOPNOTSUPP
|| errno
== ENOTTY
290 || errno
== EINVAL
|| errno
== ENODEV
298 error (0, errno
, _("cannot do ioctl on `%s'"), infile
);
300 newlines2
= newlines
;
307 int n_write
= bpout
- outbuf
;
309 if (full_write (output_desc
, outbuf
, n_write
) < 0)
310 error (EXIT_FAILURE
, errno
, _("write error"));
314 /* Read more input into INBUF. */
316 n_read
= safe_read (input_desc
, inbuf
, insize
);
319 error (0, errno
, "%s", infile
);
321 newlines2
= newlines
;
326 newlines2
= newlines
;
330 /* Update the pointers and insert a sentinel at the buffer
339 /* It was a real (not a sentinel) newline. */
341 /* Was the last line empty?
342 (i.e. have two or more consecutive newlines been read?) */
346 /* Are multiple adjacent empty lines to be substituted by
347 single ditto (-s), and this was the second empty line? */
349 if (squeeze_empty_lines
&& newlines
>= 2)
355 /* Are line numbers to be written at empty lines (-n)? */
357 if (numbers
&& numbers_at_empty_lines
)
360 bpout
= (unsigned char *) stpcpy ((char *) bpout
,
365 /* Output a currency symbol if requested (-e). */
370 /* Output the newline. */
378 /* Are we at the beginning of a line, and line numbers are requested? */
380 if (newlines
>= 0 && numbers
)
383 bpout
= (unsigned char *) stpcpy ((char *) bpout
, line_num_print
);
386 /* Here CH cannot contain a newline character. */
388 /* The loops below continue until a newline character is found,
389 which means that the buffer is empty or that a proper newline
392 /* If quoting, i.e. at least one of -v, -e, or -t specified,
393 scan for chars that need conversion. */
424 *bpout
++ = ch
- 128 + 64;
428 else if (ch
== '\t' && output_tabs
)
446 /* Not quoting, neither of -v, -e, or -t specified. */
449 if (ch
== '\t' && !output_tabs
)
469 main (int argc
, char **argv
)
471 /* Optimal size of i/o operations of output. */
474 /* Optimal size of i/o operations of input. */
477 /* Pointer to the input buffer. */
478 unsigned char *inbuf
;
480 /* Pointer to the output buffer. */
481 unsigned char *outbuf
;
485 /* Index in argv to processed argument. */
488 /* Device number of the output (file or whatever). */
491 /* I-node number of the output. */
494 /* Nonzero if the output file should not be the same as any input file. */
495 int check_redirection
= 1;
497 /* Nonzero if we have ever read standard input. */
498 int have_read_stdin
= 0;
500 struct stat stat_buf
;
502 /* Variables that are set according to the specified options. */
504 int numbers_at_empty_lines
= 1;
505 int squeeze_empty_lines
= 0;
506 int mark_line_ends
= 0;
510 int binary_files
= 0;
511 int binary_output
= 0;
513 int file_open_mode
= O_RDONLY
;
515 /* If nonzero, call cat, otherwise call simple_cat to do the actual work. */
518 static struct option
const long_options
[] =
520 {"number-nonblank", no_argument
, NULL
, 'b'},
521 {"number", no_argument
, NULL
, 'n'},
522 {"squeeze-blank", no_argument
, NULL
, 's'},
523 {"show-nonprinting", no_argument
, NULL
, 'v'},
524 {"show-ends", no_argument
, NULL
, 'E'},
525 {"show-tabs", no_argument
, NULL
, 'T'},
526 {"show-all", no_argument
, NULL
, 'A'},
528 {"binary", no_argument
, NULL
, 'B'},
530 {GETOPT_HELP_OPTION_DECL
},
531 {GETOPT_VERSION_OPTION_DECL
},
535 program_name
= argv
[0];
536 setlocale (LC_ALL
, "");
537 bindtextdomain (PACKAGE
, LOCALEDIR
);
538 textdomain (PACKAGE
);
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. */
616 case_GETOPT_HELP_CHAR
;
618 case_GETOPT_VERSION_CHAR (PROGRAM_NAME
, AUTHORS
);
621 usage (EXIT_FAILURE
);
627 /* Get device, i-node number, and optimal blocksize of output. */
629 if (fstat (output_desc
, &stat_buf
) < 0)
630 error (EXIT_FAILURE
, errno
, _("standard output"));
632 outsize
= ST_BLKSIZE (stat_buf
);
633 /* Input file can be output file for non-regular files.
634 fstat on pipes returns S_IFSOCK on some systems, S_IFIFO
635 on others, so the checking should not be done for those types,
636 and to allow things like cat < /dev/tty > /dev/tty, checking
637 is not done for device files either. */
639 if (S_ISREG (stat_buf
.st_mode
))
641 out_dev
= stat_buf
.st_dev
;
642 out_ino
= stat_buf
.st_ino
;
646 check_redirection
= 0;
647 #ifdef lint /* Suppress `used before initialized' warning. */
654 /* We always read and write in BINARY mode, since this is the
655 best way to copy the files verbatim. Exceptions are when
656 they request line numbering, squeezing of empty lines or
657 marking lines' ends: then we use text I/O, because otherwise
658 -b, -s and -E would surprise users on DOS/Windows where a line
659 with only CR-LF is an empty line. (Besides, if they ask for
660 one of these options, they don't care much about the original
661 file contents anyway). */
662 if ((!isatty (output_desc
)
663 && !(numbers
|| squeeze_empty_lines
|| mark_line_ends
))
666 /* Switch stdout to BINARY mode. */
668 SET_BINARY (output_desc
);
669 /* When stdout is in binary mode, make sure all input files are
670 also read in binary mode. */
671 file_open_mode
|= O_BINARY
;
675 /* If they want to see the non-printables, let's show them
676 those CR characters as well, so make the input binary.
677 But keep console output in text mode, so that LF causes
678 both CR and LF on output, and the output is readable. */
679 file_open_mode
|= O_BINARY
;
682 /* Setting stdin to binary switches the console device to
683 raw I/O, which also affects stdout to console. Undo that. */
684 if (isatty (output_desc
))
685 setmode (output_desc
, O_TEXT
);
689 /* Check if any of the input files are the same as the output file. */
699 infile
= argv
[argind
];
701 if (infile
[0] == '-' && infile
[1] == 0)
707 /* Switch stdin to BINARY mode if needed. */
710 int tty_in
= isatty (input_desc
);
712 /* If stdin is a terminal device, and it is the ONLY
713 input file (i.e. we didn't write anything to the
714 output yet), switch the output back to TEXT mode.
715 This is so "cat > xyzzy" creates a DOS-style text
716 file, like people expect. */
717 if (tty_in
&& optind
<= argc
)
718 setmode (output_desc
, O_TEXT
);
721 SET_BINARY (input_desc
);
723 /* This is DJGPP-specific. By default, switching console
724 to binary mode disables SIGINT. But we want terminal
725 reads to be interruptible. */
727 __djgpp_set_ctrl_c (1);
735 input_desc
= open (infile
, file_open_mode
);
738 error (0, errno
, "%s", infile
);
744 if (fstat (input_desc
, &stat_buf
) < 0)
746 error (0, errno
, "%s", infile
);
750 insize
= ST_BLKSIZE (stat_buf
);
752 /* Compare the device and i-node numbers of this input file with
753 the corresponding values of the (output file associated with)
754 stdout, and skip this input file if they coincide. Input
755 files cannot be redirected to themselves. */
757 if (check_redirection
758 && stat_buf
.st_dev
== out_dev
&& stat_buf
.st_ino
== out_ino
759 && (input_desc
!= STDIN_FILENO
|| output_desc
!= STDOUT_FILENO
))
761 error (0, 0, _("%s: input file is output file"), infile
);
766 /* Select which version of `cat' to use. If any options (more than -u,
767 --version, or --help) were specified, use `cat', otherwise use
772 insize
= max (insize
, outsize
);
773 inbuf
= (unsigned char *) xmalloc (insize
);
775 simple_cat (inbuf
, insize
);
779 inbuf
= (unsigned char *) xmalloc (insize
+ 1);
781 /* Why are (OUTSIZE - 1 + INSIZE * 4 + 13) bytes allocated for
784 A test whether output needs to be written is done when the input
785 buffer empties or when a newline appears in the input. After
786 output is written, at most (OUTSIZE - 1) bytes will remain in the
787 buffer. Now INSIZE bytes of input is read. Each input character
788 may grow by a factor of 4 (by the prepending of M-^). If all
789 characters do, and no newlines appear in this block of input, we
790 will have at most (OUTSIZE - 1 + INSIZE) bytes in the buffer. If
791 the last character in the preceding block of input was a
792 newline, a line number may be written (according to the given
793 options) as the first thing in the output buffer. (Done after the
794 new input is read, but before processing of the input begins.) A
795 line number requires seldom more than 13 positions. */
797 outbuf
= (unsigned char *) xmalloc (outsize
- 1 + insize
* 4 + 13);
799 cat (inbuf
, insize
, outbuf
, outsize
, quote
,
800 output_tabs
, numbers
, numbers_at_empty_lines
, mark_line_ends
,
801 squeeze_empty_lines
);
809 if (!STREQ (infile
, "-") && close (input_desc
) < 0)
811 error (0, errno
, "%s", infile
);
815 while (++argind
< argc
);
817 if (have_read_stdin
&& close (0) < 0)
818 error (EXIT_FAILURE
, errno
, "-");
820 error (EXIT_FAILURE
, errno
, _("write error"));
822 exit (exit_status
== 0 ? EXIT_SUCCESS
: EXIT_FAILURE
);