1 /* cat -- concatenate files and print on the standard output.
2 Copyright (C) 88, 90, 91, 1995-2000 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 "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 and Richard M. Stallman"
43 /* Undefine, to avoid warning about redefinition on some systems. */
45 #define max(h,i) ((h) > (i) ? (h) : (i))
49 /* Name under which this program was invoked. */
52 /* Name of input file. May be "-". */
55 /* Descriptor on which input file is open. */
56 static int input_desc
;
58 /* Buffer for line numbers.
59 An 11 digit counter may overflow within an hour on a P2/466,
60 an 18 digit counter needs about 1000y */
61 #define LINE_COUNTER_BUF_LEN 20
62 static char line_buf
[LINE_COUNTER_BUF_LEN
] =
64 ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
65 ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '0',
69 /* Position in `line_buf' where printing starts. This will not change
70 unless the number of lines is larger than 999999. */
71 static char *line_num_print
= line_buf
+ LINE_COUNTER_BUF_LEN
- 8;
73 /* Position of the first digit in `line_buf'. */
74 static char *line_num_start
= line_buf
+ LINE_COUNTER_BUF_LEN
- 3;
76 /* Position of the last digit in `line_buf'. */
77 static char *line_num_end
= line_buf
+ LINE_COUNTER_BUF_LEN
- 3;
79 /* Preserves the `cat' function's local `newlines' between invocations. */
80 static int newlines2
= 0;
82 /* Count of non-fatal error conditions. */
83 static int exit_status
= 0;
89 fprintf (stderr
, _("Try `%s --help' for more information.\n"),
94 Usage: %s [OPTION] [FILE]...\n\
98 Concatenate FILE(s), or standard input, to standard output.\n\
100 -A, --show-all equivalent to -vET\n\
101 -b, --number-nonblank number nonblank output lines\n\
102 -e equivalent to -vE\n\
103 -E, --show-ends display $ at end of each line\n\
104 -n, --number number all output lines\n\
105 -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\
110 --help display this help and exit\n\
111 --version output version information and exit\n\
113 With no FILE, or when FILE is -, read standard input.\n\
118 -B, --binary use binary writes to the console device.\n\n\
121 puts (_("\nReport bugs to <bug-textutils@gnu.org>."));
123 exit (status
== 0 ? EXIT_SUCCESS
: EXIT_FAILURE
);
126 /* Compute the next line number. */
131 char *endp
= line_num_end
;
138 while (endp
>= line_num_start
);
139 if (line_num_start
> line_buf
)
140 *--line_num_start
= '1';
143 if (line_num_start
< line_num_print
)
147 /* Plain cat. Copies the file behind `input_desc' to STDOUT_FILENO. */
151 /* Pointer to the buffer, used by reads and writes. */
154 /* Number of characters preferably read or written by each read and write
158 /* Actual number of characters read, and therefore written. */
161 /* Loop until the end of the file. */
165 /* Read a block of input. */
167 n_read
= safe_read (input_desc
, buf
, bufsize
);
170 error (0, errno
, "%s", infile
);
175 /* End of this file? */
180 /* Write this block out. */
182 if (full_write (STDOUT_FILENO
, buf
, n_read
) < 0)
183 error (EXIT_FAILURE
, errno
, _("write error"));
187 /* Cat the file behind INPUT_DESC to the file behind OUTPUT_DESC.
188 Called if any option more than -u was specified.
190 A newline character is always put at the end of the buffer, to make
191 an explicit test for buffer end unnecessary. */
195 /* Pointer to the beginning of the input buffer. */
196 unsigned char *inbuf
,
198 /* Number of characters read in each read call. */
201 /* Pointer to the beginning of the output buffer. */
202 unsigned char *outbuf
,
204 /* Number of characters written by each write call. */
207 /* Variables that have values according to the specified options. */
211 int numbers_at_empty_lines
,
213 int squeeze_empty_lines
)
215 /* Last character read from the input buffer. */
218 /* Pointer to the next character in the input buffer. */
221 /* Pointer to the first non-valid byte in the input buffer, i.e. the
222 current end of the buffer. */
225 /* Pointer to the position where the next character shall be written. */
226 unsigned char *bpout
;
228 /* Number of characters read by the last read call. */
231 /* Determines how many consecutive newlines there have been in the
232 input. 0 newlines makes NEWLINES -1, 1 newline makes NEWLINES 1,
233 etc. Initially 0 to indicate that we are at the beginning of a
234 new line. The "state" of the procedure is determined by
236 int newlines
= newlines2
;
239 /* If nonzero, use the FIONREAD ioctl, as an optimization.
240 (On Ultrix, it is not supported on NFS filesystems.) */
241 int use_fionread
= 1;
244 /* The inbuf pointers are initialized so that BPIN > EOB, and thereby input
245 is read immediately. */
256 /* Write if there are at least OUTSIZE bytes in OUTBUF. */
258 if (bpout
- outbuf
>= outsize
)
260 unsigned char *wp
= outbuf
;
263 if (full_write (STDOUT_FILENO
, wp
, outsize
) < 0)
264 error (EXIT_FAILURE
, errno
, _("write error"));
267 while (bpout
- wp
>= outsize
);
269 /* Move the remaining bytes to the beginning of the
272 memmove (outbuf
, wp
, bpout
- wp
);
273 bpout
= outbuf
+ (bpout
- wp
);
276 /* Is INBUF empty? */
283 /* Is there any input to read immediately?
284 If not, we are about to wait,
285 so write all buffered output before waiting. */
288 && ioctl (input_desc
, FIONREAD
, &n_to_read
) < 0)
290 /* Ultrix returns EOPNOTSUPP on NFS;
291 HP-UX returns ENOTTY on pipes.
292 SunOS returns EINVAL and
293 More/BSD returns ENODEV on special files
295 Irix-5 returns ENOSYS on pipes. */
296 if (errno
== EOPNOTSUPP
|| errno
== ENOTTY
297 || errno
== EINVAL
|| errno
== ENODEV
305 error (0, errno
, _("cannot do ioctl on `%s'"), infile
);
307 newlines2
= newlines
;
314 int n_write
= bpout
- outbuf
;
316 if (full_write (STDOUT_FILENO
, outbuf
, n_write
) < 0)
317 error (EXIT_FAILURE
, errno
, _("write error"));
321 /* Read more input into INBUF. */
323 n_read
= safe_read (input_desc
, inbuf
, insize
);
326 error (0, errno
, "%s", infile
);
328 newlines2
= newlines
;
333 newlines2
= newlines
;
337 /* Update the pointers and insert a sentinel at the buffer
346 /* It was a real (not a sentinel) newline. */
348 /* Was the last line empty?
349 (i.e. have two or more consecutive newlines been read?) */
355 /* Limit this to 2 here. Otherwise, with lots of
356 consecutive newlines, the counter could wrap
357 around at INT_MAX. */
360 /* Are multiple adjacent empty lines to be substituted
361 by single ditto (-s), and this was the second empty
363 if (squeeze_empty_lines
)
370 /* Are line numbers to be written at empty lines (-n)? */
372 if (numbers
&& numbers_at_empty_lines
)
375 bpout
= (unsigned char *) stpcpy ((char *) bpout
,
380 /* Output a currency symbol if requested (-e). */
385 /* Output the newline. */
393 /* Are we at the beginning of a line, and line numbers are requested? */
395 if (newlines
>= 0 && numbers
)
398 bpout
= (unsigned char *) stpcpy ((char *) bpout
, line_num_print
);
401 /* Here CH cannot contain a newline character. */
403 /* The loops below continue until a newline character is found,
404 which means that the buffer is empty or that a proper newline
407 /* If quoting, i.e. at least one of -v, -e, or -t specified,
408 scan for chars that need conversion. */
439 *bpout
++ = ch
- 128 + 64;
443 else if (ch
== '\t' && output_tabs
)
461 /* Not quoting, neither of -v, -e, or -t specified. */
464 if (ch
== '\t' && !output_tabs
)
484 main (int argc
, char **argv
)
486 /* Optimal size of i/o operations of output. */
489 /* Optimal size of i/o operations of input. */
492 /* Pointer to the input buffer. */
493 unsigned char *inbuf
;
495 /* Pointer to the output buffer. */
496 unsigned char *outbuf
;
500 /* Index in argv to processed argument. */
503 /* Device number of the output (file or whatever). */
506 /* I-node number of the output. */
509 /* Nonzero if the output file should not be the same as any input file. */
510 int check_redirection
= 1;
512 /* Nonzero if we have ever read standard input. */
513 int have_read_stdin
= 0;
515 struct stat stat_buf
;
517 /* Variables that are set according to the specified options. */
519 int numbers_at_empty_lines
= 1;
520 int squeeze_empty_lines
= 0;
521 int mark_line_ends
= 0;
525 int binary_files
= 0;
526 int binary_output
= 0;
528 int file_open_mode
= O_RDONLY
;
530 /* If nonzero, call cat, otherwise call simple_cat to do the actual work. */
533 static struct option
const long_options
[] =
535 {"number-nonblank", no_argument
, NULL
, 'b'},
536 {"number", no_argument
, NULL
, 'n'},
537 {"squeeze-blank", no_argument
, NULL
, 's'},
538 {"show-nonprinting", no_argument
, NULL
, 'v'},
539 {"show-ends", no_argument
, NULL
, 'E'},
540 {"show-tabs", no_argument
, NULL
, 'T'},
541 {"show-all", no_argument
, NULL
, 'A'},
543 {"binary", no_argument
, NULL
, 'B'},
545 {GETOPT_HELP_OPTION_DECL
},
546 {GETOPT_VERSION_OPTION_DECL
},
550 program_name
= argv
[0];
551 setlocale (LC_ALL
, "");
552 bindtextdomain (PACKAGE
, LOCALEDIR
);
553 textdomain (PACKAGE
);
555 atexit (close_stdout
);
557 /* Parse command line options. */
559 while ((c
= getopt_long (argc
, argv
,
565 , long_options
, NULL
)) != -1)
575 numbers_at_empty_lines
= 0;
591 squeeze_empty_lines
= 1;
601 /* We provide the -u feature unconditionally. */
633 case_GETOPT_HELP_CHAR
;
635 case_GETOPT_VERSION_CHAR (PROGRAM_NAME
, AUTHORS
);
638 usage (EXIT_FAILURE
);
642 /* Get device, i-node number, and optimal blocksize of output. */
644 if (fstat (STDOUT_FILENO
, &stat_buf
) < 0)
645 error (EXIT_FAILURE
, errno
, _("standard output"));
647 outsize
= ST_BLKSIZE (stat_buf
);
648 /* Input file can be output file for non-regular files.
649 fstat on pipes returns S_IFSOCK on some systems, S_IFIFO
650 on others, so the checking should not be done for those types,
651 and to allow things like cat < /dev/tty > /dev/tty, checking
652 is not done for device files either. */
654 if (S_ISREG (stat_buf
.st_mode
))
656 out_dev
= stat_buf
.st_dev
;
657 out_ino
= stat_buf
.st_ino
;
661 check_redirection
= 0;
662 #ifdef lint /* Suppress `used before initialized' warning. */
669 /* We always read and write in BINARY mode, since this is the
670 best way to copy the files verbatim. Exceptions are when
671 they request line numbering, squeezing of empty lines or
672 marking lines' ends: then we use text I/O, because otherwise
673 -b, -s and -E would surprise users on DOS/Windows where a line
674 with only CR-LF is an empty line. (Besides, if they ask for
675 one of these options, they don't care much about the original
676 file contents anyway). */
677 if ((!isatty (STDOUT_FILENO
)
678 && !(numbers
|| squeeze_empty_lines
|| mark_line_ends
))
681 /* Switch stdout to BINARY mode. */
683 SET_BINARY (STDOUT_FILENO
);
684 /* When stdout is in binary mode, make sure all input files are
685 also read in binary mode. */
686 file_open_mode
|= O_BINARY
;
690 /* If they want to see the non-printables, let's show them
691 those CR characters as well, so make the input binary.
692 But keep console output in text mode, so that LF causes
693 both CR and LF on output, and the output is readable. */
694 file_open_mode
|= O_BINARY
;
697 /* Setting stdin to binary switches the console device to
698 raw I/O, which also affects stdout to console. Undo that. */
699 if (isatty (STDOUT_FILENO
))
700 setmode (STDOUT_FILENO
, O_TEXT
);
704 /* Check if any of the input files are the same as the output file. */
714 infile
= argv
[argind
];
716 if (infile
[0] == '-' && infile
[1] == 0)
722 /* Switch stdin to BINARY mode if needed. */
725 int tty_in
= isatty (input_desc
);
727 /* If stdin is a terminal device, and it is the ONLY
728 input file (i.e. we didn't write anything to the
729 output yet), switch the output back to TEXT mode.
730 This is so "cat > xyzzy" creates a DOS-style text
731 file, like people expect. */
732 if (tty_in
&& optind
<= argc
)
733 setmode (STDOUT_FILENO
, O_TEXT
);
736 SET_BINARY (input_desc
);
738 /* This is DJGPP-specific. By default, switching console
739 to binary mode disables SIGINT. But we want terminal
740 reads to be interruptible. */
742 __djgpp_set_ctrl_c (1);
750 input_desc
= open (infile
, file_open_mode
);
753 error (0, errno
, "%s", infile
);
759 if (fstat (input_desc
, &stat_buf
) < 0)
761 error (0, errno
, "%s", infile
);
765 insize
= ST_BLKSIZE (stat_buf
);
767 /* Compare the device and i-node numbers of this input file with
768 the corresponding values of the (output file associated with)
769 stdout, and skip this input file if they coincide. Input
770 files cannot be redirected to themselves. */
772 if (check_redirection
773 && stat_buf
.st_dev
== out_dev
&& stat_buf
.st_ino
== out_ino
774 && (input_desc
!= STDIN_FILENO
))
776 error (0, 0, _("%s: input file is output file"), infile
);
781 /* Select which version of `cat' to use. If any options (more than -u,
782 --version, or --help) were specified, use `cat', otherwise use
787 insize
= max (insize
, outsize
);
788 inbuf
= (unsigned char *) xmalloc (insize
);
790 simple_cat (inbuf
, insize
);
794 inbuf
= (unsigned char *) xmalloc (insize
+ 1);
796 /* Why are (OUTSIZE - 1 + INSIZE * 4 + LINE_COUNTER_BUF_LEN)
797 bytes allocated for the output buffer?
799 A test whether output needs to be written is done when the input
800 buffer empties or when a newline appears in the input. After
801 output is written, at most (OUTSIZE - 1) bytes will remain in the
802 buffer. Now INSIZE bytes of input is read. Each input character
803 may grow by a factor of 4 (by the prepending of M-^). If all
804 characters do, and no newlines appear in this block of input, we
805 will have at most (OUTSIZE - 1 + INSIZE * 4) bytes in the buffer.
806 If the last character in the preceding block of input was a
807 newline, a line number may be written (according to the given
808 options) as the first thing in the output buffer. (Done after the
809 new input is read, but before processing of the input begins.)
810 A line number requires seldom more than LINE_COUNTER_BUF_LEN
813 outbuf
= (unsigned char *) xmalloc (outsize
- 1 + insize
* 4
814 + LINE_COUNTER_BUF_LEN
);
816 cat (inbuf
, insize
, outbuf
, outsize
, quote
,
817 output_tabs
, numbers
, numbers_at_empty_lines
, mark_line_ends
,
818 squeeze_empty_lines
);
826 if (!STREQ (infile
, "-") && close (input_desc
) < 0)
828 error (0, errno
, "%s", infile
);
832 while (++argind
< argc
);
834 if (have_read_stdin
&& close (0) < 0)
835 error (EXIT_FAILURE
, errno
, "-");
837 exit (exit_status
== 0 ? EXIT_SUCCESS
: EXIT_FAILURE
);