1 /* cat -- concatenate files and print on the standard output.
2 Copyright (C) 88, 90, 91, 1995-1998, 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 /* Undefine, to avoid warning about redefinition on some systems. */
39 #define max(h,i) ((h) > (i) ? (h) : (i))
43 /* Name under which this program was invoked. */
46 /* Name of input file. May be "-". */
49 /* Descriptor on which input file is open. */
50 static int input_desc
;
52 /* Descriptor on which output file is open. Always is 1. */
53 static int output_desc
;
55 /* Buffer for line numbers. */
56 static char line_buf
[13] =
57 {' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '0', '\t', '\0'};
59 /* Position in `line_buf' where printing starts. This will not change
60 unless the number of lines is larger than 999999. */
61 static char *line_num_print
= line_buf
+ 5;
63 /* Position of the first digit in `line_buf'. */
64 static char *line_num_start
= line_buf
+ 10;
66 /* Position of the last digit in `line_buf'. */
67 static char *line_num_end
= line_buf
+ 10;
69 /* Preserves the `cat' function's local `newlines' between invocations. */
70 static int newlines2
= 0;
72 /* Count of non-fatal error conditions. */
73 static int exit_status
= 0;
79 fprintf (stderr
, _("Try `%s --help' for more information.\n"),
84 Usage: %s [OPTION] [FILE]...\n\
88 Concatenate FILE(s), or standard input, to standard output.\n\
90 -A, --show-all equivalent to -vET\n\
91 -b, --number-nonblank number nonblank output lines\n\
92 -e equivalent to -vE\n\
93 -E, --show-ends display $ at end of each line\n\
94 -n, --number number all output lines\n\
95 -s, --squeeze-blank never more than one single blank line\n\
96 -t equivalent to -vT\n\
97 -T, --show-tabs display TAB characters as ^I\n\
99 -v, --show-nonprinting use ^ and M- notation, except for LFD and TAB\n\
100 --help display this help and exit\n\
101 --version output version information and exit\n\
103 With no FILE, or when FILE is -, read standard input.\n\
108 -B, --binary use binary writes to the console device.\n\n\
111 puts (_("\nReport bugs to <bug-textutils@gnu.org>."));
113 exit (status
== 0 ? EXIT_SUCCESS
: EXIT_FAILURE
);
116 /* Compute the next line number. */
121 char *endp
= line_num_end
;
128 while (endp
>= line_num_start
);
129 *--line_num_start
= '1';
130 if (line_num_start
< line_num_print
)
134 /* Plain cat. Copies the file behind `input_desc' to the file behind
139 /* Pointer to the buffer, used by reads and writes. */
142 /* Number of characters preferably read or written by each read and write
146 /* Actual number of characters read, and therefore written. */
149 /* Loop until the end of the file. */
153 /* Read a block of input. */
155 n_read
= safe_read (input_desc
, buf
, bufsize
);
158 error (0, errno
, "%s", infile
);
163 /* End of this file? */
168 /* Write this block out. */
170 if (full_write (output_desc
, buf
, n_read
) < 0)
171 error (EXIT_FAILURE
, errno
, _("write error"));
175 /* Cat the file behind INPUT_DESC to the file behind OUTPUT_DESC.
176 Called if any option more than -u was specified.
178 A newline character is always put at the end of the buffer, to make
179 an explicit test for buffer end unnecessary. */
183 /* Pointer to the beginning of the input buffer. */
184 unsigned char *inbuf
,
186 /* Number of characters read in each read call. */
189 /* Pointer to the beginning of the output buffer. */
190 unsigned char *outbuf
,
192 /* Number of characters written by each write call. */
195 /* Variables that have values according to the specified options. */
199 int numbers_at_empty_lines
,
201 int squeeze_empty_lines
)
203 /* Last character read from the input buffer. */
206 /* Pointer to the next character in the input buffer. */
209 /* Pointer to the first non-valid byte in the input buffer, i.e. the
210 current end of the buffer. */
213 /* Pointer to the position where the next character shall be written. */
214 unsigned char *bpout
;
216 /* Number of characters read by the last read call. */
219 /* Determines how many consecutive newlines there have been in the
220 input. 0 newlines makes NEWLINES -1, 1 newline makes NEWLINES 1,
221 etc. Initially 0 to indicate that we are at the beginning of a
222 new line. The "state" of the procedure is determined by
224 int newlines
= newlines2
;
227 /* If nonzero, use the FIONREAD ioctl, as an optimization.
228 (On Ultrix, it is not supported on NFS filesystems.) */
229 int use_fionread
= 1;
232 /* The inbuf pointers are initialized so that BPIN > EOB, and thereby input
233 is read immediately. */
244 /* Write if there are at least OUTSIZE bytes in OUTBUF. */
246 if (bpout
- outbuf
>= outsize
)
248 unsigned char *wp
= outbuf
;
251 if (full_write (output_desc
, wp
, outsize
) < 0)
252 error (EXIT_FAILURE
, errno
, _("write error"));
255 while (bpout
- wp
>= outsize
);
257 /* Move the remaining bytes to the beginning of the
260 memmove (outbuf
, wp
, bpout
- wp
);
261 bpout
= outbuf
+ (bpout
- wp
);
264 /* Is INBUF empty? */
271 /* Is there any input to read immediately?
272 If not, we are about to wait,
273 so write all buffered output before waiting. */
276 && ioctl (input_desc
, FIONREAD
, &n_to_read
) < 0)
278 /* Ultrix returns EOPNOTSUPP on NFS;
279 HP-UX returns ENOTTY on pipes.
280 SunOS returns EINVAL and
281 More/BSD returns ENODEV on special files
283 Irix-5 returns ENOSYS on pipes. */
284 if (errno
== EOPNOTSUPP
|| errno
== ENOTTY
285 || errno
== EINVAL
|| errno
== ENODEV
293 error (0, errno
, _("cannot do ioctl on `%s'"), infile
);
295 newlines2
= newlines
;
302 int n_write
= bpout
- outbuf
;
304 if (full_write (output_desc
, outbuf
, n_write
) < 0)
305 error (EXIT_FAILURE
, errno
, _("write error"));
309 /* Read more input into INBUF. */
311 n_read
= safe_read (input_desc
, inbuf
, insize
);
314 error (0, errno
, "%s", infile
);
316 newlines2
= newlines
;
321 newlines2
= newlines
;
325 /* Update the pointers and insert a sentinel at the buffer
334 /* It was a real (not a sentinel) newline. */
336 /* Was the last line empty?
337 (i.e. have two or more consecutive newlines been read?) */
341 /* Are multiple adjacent empty lines to be substituted by
342 single ditto (-s), and this was the second empty line? */
344 if (squeeze_empty_lines
&& newlines
>= 2)
350 /* Are line numbers to be written at empty lines (-n)? */
352 if (numbers
&& numbers_at_empty_lines
)
355 bpout
= (unsigned char *) stpcpy ((char *) bpout
,
360 /* Output a currency symbol if requested (-e). */
365 /* Output the newline. */
373 /* Are we at the beginning of a line, and line numbers are requested? */
375 if (newlines
>= 0 && numbers
)
378 bpout
= (unsigned char *) stpcpy ((char *) bpout
, line_num_print
);
381 /* Here CH cannot contain a newline character. */
383 /* The loops below continue until a newline character is found,
384 which means that the buffer is empty or that a proper newline
387 /* If quoting, i.e. at least one of -v, -e, or -t specified,
388 scan for chars that need conversion. */
419 *bpout
++ = ch
- 128 + 64;
423 else if (ch
== '\t' && output_tabs
)
441 /* Not quoting, neither of -v, -e, or -t specified. */
444 if (ch
== '\t' && !output_tabs
)
464 main (int argc
, char **argv
)
466 /* Optimal size of i/o operations of output. */
469 /* Optimal size of i/o operations of input. */
472 /* Pointer to the input buffer. */
473 unsigned char *inbuf
;
475 /* Pointer to the output buffer. */
476 unsigned char *outbuf
;
480 /* Index in argv to processed argument. */
483 /* Device number of the output (file or whatever). */
486 /* I-node number of the output. */
489 /* Nonzero if the output file should not be the same as any input file. */
490 int check_redirection
= 1;
492 /* Nonzero if we have ever read standard input. */
493 int have_read_stdin
= 0;
495 struct stat stat_buf
;
497 /* Variables that are set according to the specified options. */
499 int numbers_at_empty_lines
= 1;
500 int squeeze_empty_lines
= 0;
501 int mark_line_ends
= 0;
505 int binary_files
= 0;
506 int binary_output
= 0;
508 int file_open_mode
= O_RDONLY
;
510 /* If nonzero, call cat, otherwise call simple_cat to do the actual work. */
513 /* If nonzero, display usage information and exit. */
514 static int show_help
;
516 /* If nonzero, print the version on standard output then exit. */
517 static int show_version
;
519 static struct option
const long_options
[] =
521 {"number-nonblank", no_argument
, NULL
, 'b'},
522 {"number", no_argument
, NULL
, 'n'},
523 {"squeeze-blank", no_argument
, NULL
, 's'},
524 {"show-nonprinting", no_argument
, NULL
, 'v'},
525 {"show-ends", no_argument
, NULL
, 'E'},
526 {"show-tabs", no_argument
, NULL
, 'T'},
527 {"show-all", no_argument
, NULL
, 'A'},
529 {"binary", no_argument
, NULL
, 'B'},
531 {"help", no_argument
, &show_help
, 1},
532 {"version", no_argument
, &show_version
, 1},
536 program_name
= argv
[0];
537 setlocale (LC_ALL
, "");
538 bindtextdomain (PACKAGE
, LOCALEDIR
);
539 textdomain (PACKAGE
);
541 /* Parse command line options. */
543 while ((c
= getopt_long (argc
, argv
,
549 , long_options
, NULL
)) != -1)
559 numbers_at_empty_lines
= 0;
575 squeeze_empty_lines
= 1;
585 /* We provide the -u feature unconditionally. */
618 usage (EXIT_FAILURE
);
624 printf ("cat (%s) %s\n", GNU_PACKAGE
, VERSION
);
633 /* Get device, i-node number, and optimal blocksize of output. */
635 if (fstat (output_desc
, &stat_buf
) < 0)
636 error (EXIT_FAILURE
, errno
, _("standard output"));
638 outsize
= ST_BLKSIZE (stat_buf
);
639 /* Input file can be output file for non-regular files.
640 fstat on pipes returns S_IFSOCK on some systems, S_IFIFO
641 on others, so the checking should not be done for those types,
642 and to allow things like cat < /dev/tty > /dev/tty, checking
643 is not done for device files either. */
645 if (S_ISREG (stat_buf
.st_mode
))
647 out_dev
= stat_buf
.st_dev
;
648 out_ino
= stat_buf
.st_ino
;
652 check_redirection
= 0;
653 #ifdef lint /* Suppress `used before initialized' warning. */
660 /* We always read and write in BINARY mode, since this is the
661 best way to copy the files verbatim. Exceptions are when
662 they request line numbering, squeezing of empty lines or
663 marking lines' ends: then we use text I/O, because otherwise
664 -b, -s and -E would surprise users on DOS/Windows where a line
665 with only CR-LF is an empty line. (Besides, if they ask for
666 one of these options, they don't care much about the original
667 file contents anyway). */
668 if ((!isatty (output_desc
)
669 && !(numbers
|| squeeze_empty_lines
|| mark_line_ends
))
672 /* Switch stdout to BINARY mode. */
674 SET_BINARY (output_desc
);
678 /* If they want to see the non-printables, let's show them
679 those CR characters as well, so make the input binary.
680 But keep console output in text mode, so that LF causes
681 both CR and LF on output, and the output is readable. */
682 file_open_mode
|= O_BINARY
;
685 /* Setting stdin to binary switches the console device to
686 raw I/O, which also affects stdout to console. Undo that. */
687 if (isatty (output_desc
))
688 setmode (output_desc
, O_TEXT
);
692 /* Check if any of the input files are the same as the output file. */
702 infile
= argv
[argind
];
704 if (infile
[0] == '-' && infile
[1] == 0)
710 /* Switch stdin to BINARY mode if needed. */
713 int tty_in
= isatty (input_desc
);
715 /* If stdin is a terminal device, and it is the ONLY
716 input file (i.e. we didn't write anything to the
717 output yet), switch the output back to TEXT mode.
718 This is so "cat > xyzzy" creates a DOS-style text
719 file, like people expect. */
720 if (tty_in
&& optind
<= argc
)
721 setmode (output_desc
, O_TEXT
);
724 SET_BINARY (input_desc
);
726 /* This is DJGPP-specific. By default, switching console
727 to binary mode disables SIGINT. But we want terminal
728 reads to be interruptible. */
730 __djgpp_set_ctrl_c (1);
738 input_desc
= open (infile
, file_open_mode
);
741 error (0, errno
, "%s", infile
);
747 if (fstat (input_desc
, &stat_buf
) < 0)
749 error (0, errno
, "%s", infile
);
753 insize
= ST_BLKSIZE (stat_buf
);
755 /* Compare the device and i-node numbers of this input file with
756 the corresponding values of the (output file associated with)
757 stdout, and skip this input file if they coincide. Input
758 files cannot be redirected to themselves. */
760 if (check_redirection
761 && stat_buf
.st_dev
== out_dev
&& stat_buf
.st_ino
== out_ino
762 && (input_desc
!= STDIN_FILENO
|| output_desc
!= STDOUT_FILENO
))
764 error (0, 0, _("%s: input file is output file"), infile
);
769 /* Select which version of `cat' to use. If any options (more than -u,
770 --version, or --help) were specified, use `cat', otherwise use
775 insize
= max (insize
, outsize
);
776 inbuf
= (unsigned char *) xmalloc (insize
);
778 simple_cat (inbuf
, insize
);
782 inbuf
= (unsigned char *) xmalloc (insize
+ 1);
784 /* Why are (OUTSIZE - 1 + INSIZE * 4 + 13) bytes allocated for
787 A test whether output needs to be written is done when the input
788 buffer empties or when a newline appears in the input. After
789 output is written, at most (OUTSIZE - 1) bytes will remain in the
790 buffer. Now INSIZE bytes of input is read. Each input character
791 may grow by a factor of 4 (by the prepending of M-^). If all
792 characters do, and no newlines appear in this block of input, we
793 will have at most (OUTSIZE - 1 + INSIZE) bytes in the buffer. If
794 the last character in the preceding block of input was a
795 newline, a line number may be written (according to the given
796 options) as the first thing in the output buffer. (Done after the
797 new input is read, but before processing of the input begins.) A
798 line number requires seldom more than 13 positions. */
800 outbuf
= (unsigned char *) xmalloc (outsize
- 1 + insize
* 4 + 13);
802 cat (inbuf
, insize
, outbuf
, outsize
, quote
,
803 output_tabs
, numbers
, numbers_at_empty_lines
, mark_line_ends
,
804 squeeze_empty_lines
);
812 if (!STREQ (infile
, "-") && close (input_desc
) < 0)
814 error (0, errno
, "%s", infile
);
818 while (++argind
< argc
);
820 if (have_read_stdin
&& close (0) < 0)
821 error (EXIT_FAILURE
, errno
, "-");
823 error (EXIT_FAILURE
, errno
, _("write error"));
825 exit (exit_status
== 0 ? EXIT_SUCCESS
: EXIT_FAILURE
);