1 /* cat -- concatenate files and print on the standard output.
2 Copyright (C) 88, 90, 91, 1995-2007 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 3 of the License, or
7 (at your option) any later version.
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, see <http://www.gnu.org/licenses/>. */
17 /* Differences from the Unix cat:
18 * Always unbuffered, -u is ignored.
19 * Usually much faster than other versions of cat, the difference
20 is especially apparent when using the -v option.
22 By tege@sics.se, Torbjorn Granlund, advised by rms, Richard Stallman. */
28 #include <sys/types.h>
34 # include <sys/ioctl.h>
39 #include "full-write.h"
41 #include "safe-read.h"
43 /* The official name of this program (e.g., no `g' prefix). */
44 #define PROGRAM_NAME "cat"
46 #define AUTHORS "Torbjorn Granlund", "Richard M. Stallman"
48 /* Undefine, to avoid warning about redefinition on some systems. */
50 #define max(h,i) ((h) > (i) ? (h) : (i))
52 /* Name under which this program was invoked. */
55 /* Name of input file. May be "-". */
56 static char const *infile;
58 /* Descriptor on which input file is open. */
59 static int input_desc;
61 /* Buffer for line numbers.
62 An 11 digit counter may overflow within an hour on a P2/466,
63 an 18 digit counter needs about 1000y */
64 #define LINE_COUNTER_BUF_LEN 20
65 static char line_buf[LINE_COUNTER_BUF_LEN] =
67 ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
68 ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '0',
72 /* Position in `line_buf' where printing starts. This will not change
73 unless the number of lines is larger than 999999. */
74 static char *line_num_print = line_buf + LINE_COUNTER_BUF_LEN - 8;
76 /* Position of the first digit in `line_buf'. */
77 static char *line_num_start = line_buf + LINE_COUNTER_BUF_LEN - 3;
79 /* Position of the last digit in `line_buf'. */
80 static char *line_num_end = line_buf + LINE_COUNTER_BUF_LEN - 3;
82 /* Preserves the `cat' function's local `newlines' between invocations. */
83 static int newlines2 = 0;
88 if (status != EXIT_SUCCESS)
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 nonempty 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 suppress repeated empty output lines\n\
108 -t equivalent to -vT\n\
109 -T, --show-tabs display TAB characters as ^I\n\
111 -v, --show-nonprinting use ^ and M- notation, except for LFD and TAB\n\
113 fputs (HELP_OPTION_DESCRIPTION, stdout);
114 fputs (VERSION_OPTION_DESCRIPTION, stdout);
117 With no FILE, or when FILE is -, read standard input.\n\
122 %s f - g Output f's contents, then standard input, then g's contents.\n\
123 %s Copy standard input to standard output.\n\
125 program_name, program_name);
126 emit_bug_reporting_address ();
131 /* Compute the next line number. */
136 char *endp = line_num_end;
143 while (endp >= line_num_start);
144 if (line_num_start > line_buf)
145 *--line_num_start = '1';
148 if (line_num_start < line_num_print)
152 /* Plain cat. Copies the file behind `input_desc' to STDOUT_FILENO.
153 Return true if successful. */
157 /* Pointer to the buffer, used by reads and writes. */
160 /* Number of characters preferably read or written by each read and write
164 /* Actual number of characters read, and therefore written. */
167 /* Loop until the end of the file. */
171 /* Read a block of input. */
173 n_read = safe_read (input_desc, buf, bufsize);
174 if (n_read == SAFE_READ_ERROR)
176 error (0, errno, "%s", infile);
180 /* End of this file? */
185 /* Write this block out. */
188 /* The following is ok, since we know that 0 < n_read. */
190 if (full_write (STDOUT_FILENO, buf, n) != n)
191 error (EXIT_FAILURE, errno, _("write error"));
196 /* Write any pending output to STDOUT_FILENO.
197 Pending is defined to be the *BPOUT - OUTBUF bytes starting at OUTBUF.
198 Then set *BPOUT to OUTPUT if it's not already that value. */
201 write_pending (char *outbuf, char **bpout)
203 size_t n_write = *bpout - outbuf;
206 if (full_write (STDOUT_FILENO, outbuf, n_write) != n_write)
207 error (EXIT_FAILURE, errno, _("write error"));
212 /* Cat the file behind INPUT_DESC to the file behind OUTPUT_DESC.
213 Return true if successful.
214 Called if any option more than -u was specified.
216 A newline character is always put at the end of the buffer, to make
217 an explicit test for buffer end unnecessary. */
221 /* Pointer to the beginning of the input buffer. */
224 /* Number of characters read in each read call. */
227 /* Pointer to the beginning of the output buffer. */
230 /* Number of characters written by each write call. */
233 /* Variables that have values according to the specified options. */
234 bool show_nonprinting,
237 bool number_nonblank,
241 /* Last character read from the input buffer. */
244 /* Pointer to the next character in the input buffer. */
247 /* Pointer to the first non-valid byte in the input buffer, i.e. the
248 current end of the buffer. */
251 /* Pointer to the position where the next character shall be written. */
254 /* Number of characters read by the last read call. */
257 /* Determines how many consecutive newlines there have been in the
258 input. 0 newlines makes NEWLINES -1, 1 newline makes NEWLINES 1,
259 etc. Initially 0 to indicate that we are at the beginning of a
260 new line. The "state" of the procedure is determined by
262 int newlines = newlines2;
265 /* If nonzero, use the FIONREAD ioctl, as an optimization.
266 (On Ultrix, it is not supported on NFS file systems.) */
267 bool use_fionread = true;
270 /* The inbuf pointers are initialized so that BPIN > EOB, and thereby input
271 is read immediately. */
282 /* Write if there are at least OUTSIZE bytes in OUTBUF. */
284 if (outbuf + outsize <= bpout)
287 size_t remaining_bytes;
290 if (full_write (STDOUT_FILENO, wp, outsize) != outsize)
291 error (EXIT_FAILURE, errno, _("write error"));
293 remaining_bytes = bpout - wp;
295 while (outsize <= remaining_bytes);
297 /* Move the remaining bytes to the beginning of the
300 memmove (outbuf, wp, remaining_bytes);
301 bpout = outbuf + remaining_bytes;
304 /* Is INBUF empty? */
308 bool input_pending = false;
312 /* Is there any input to read immediately?
313 If not, we are about to wait,
314 so write all buffered output before waiting. */
317 && ioctl (input_desc, FIONREAD, &n_to_read) < 0)
319 /* Ultrix returns EOPNOTSUPP on NFS;
320 HP-UX returns ENOTTY on pipes.
321 SunOS returns EINVAL and
322 More/BSD returns ENODEV on special files
324 Irix-5 returns ENOSYS on pipes. */
325 if (errno == EOPNOTSUPP || errno == ENOTTY
326 || errno == EINVAL || errno == ENODEV
328 use_fionread = false;
331 error (0, errno, _("cannot do ioctl on %s"), quote (infile));
332 newlines2 = newlines;
337 input_pending = true;
341 write_pending (outbuf, &bpout);
343 /* Read more input into INBUF. */
345 n_read = safe_read (input_desc, inbuf, insize);
346 if (n_read == SAFE_READ_ERROR)
348 error (0, errno, "%s", infile);
349 write_pending (outbuf, &bpout);
350 newlines2 = newlines;
355 write_pending (outbuf, &bpout);
356 newlines2 = newlines;
360 /* Update the pointers and insert a sentinel at the buffer
369 /* It was a real (not a sentinel) newline. */
371 /* Was the last line empty?
372 (i.e. have two or more consecutive newlines been read?) */
378 /* Limit this to 2 here. Otherwise, with lots of
379 consecutive newlines, the counter could wrap
380 around at INT_MAX. */
383 /* Are multiple adjacent empty lines to be substituted
384 by single ditto (-s), and this was the second empty
393 /* Are line numbers to be written at empty lines (-n)? */
395 if (number & !number_nonblank)
398 bpout = stpcpy (bpout, line_num_print);
402 /* Output a currency symbol if requested (-e). */
407 /* Output the newline. */
415 /* Are we at the beginning of a line, and line numbers are requested? */
417 if (newlines >= 0 && number)
420 bpout = stpcpy (bpout, line_num_print);
423 /* Here CH cannot contain a newline character. */
425 /* The loops below continue until a newline character is found,
426 which means that the buffer is empty or that a proper newline
429 /* If quoting, i.e. at least one of -v, -e, or -t specified,
430 scan for chars that need conversion. */
431 if (show_nonprinting)
461 *bpout++ = ch - 128 + 64;
465 else if (ch == '\t' && !show_tabs)
483 /* Not quoting, neither of -v, -e, or -t specified. */
486 if (ch == '\t' && show_tabs)
506 main (int argc, char **argv)
508 /* Optimal size of i/o operations of output. */
511 /* Optimal size of i/o operations of input. */
514 size_t page_size = getpagesize ();
516 /* Pointer to the input buffer. */
519 /* Pointer to the output buffer. */
525 /* Index in argv to processed argument. */
528 /* Device number of the output (file or whatever). */
531 /* I-node number of the output. */
534 /* True if the output file should not be the same as any input file. */
535 bool check_redirection = true;
537 /* Nonzero if we have ever read standard input. */
538 bool have_read_stdin = false;
540 struct stat stat_buf;
542 /* Variables that are set according to the specified options. */
544 bool number_nonblank = false;
545 bool squeeze_blank = false;
546 bool show_ends = false;
547 bool show_nonprinting = false;
548 bool show_tabs = false;
549 int file_open_mode = O_RDONLY;
551 static struct option const long_options[] =
553 {"number-nonblank", no_argument, NULL, 'b'},
554 {"number", no_argument, NULL, 'n'},
555 {"squeeze-blank", no_argument, NULL, 's'},
556 {"show-nonprinting", no_argument, NULL, 'v'},
557 {"show-ends", no_argument, NULL, 'E'},
558 {"show-tabs", no_argument, NULL, 'T'},
559 {"show-all", no_argument, NULL, 'A'},
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 Normally STDOUT_FILENO is used rather than stdout, so
574 close_stdout does nothing. */
575 atexit (close_stdout);
577 /* Parse command line options. */
579 while ((c = getopt_long (argc, argv, "benstuvAET", long_options, NULL))
586 number_nonblank = true;
591 show_nonprinting = true;
599 squeeze_blank = true;
604 show_nonprinting = true;
608 /* We provide the -u feature unconditionally. */
612 show_nonprinting = true;
616 show_nonprinting = true;
629 case_GETOPT_HELP_CHAR;
631 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
634 usage (EXIT_FAILURE);
638 /* Get device, i-node number, and optimal blocksize of output. */
640 if (fstat (STDOUT_FILENO, &stat_buf) < 0)
641 error (EXIT_FAILURE, errno, _("standard output"));
643 outsize = ST_BLKSIZE (stat_buf);
644 /* Input file can be output file for non-regular files.
645 fstat on pipes returns S_IFSOCK on some systems, S_IFIFO
646 on others, so the checking should not be done for those types,
647 and to allow things like cat < /dev/tty > /dev/tty, checking
648 is not done for device files either. */
650 if (S_ISREG (stat_buf.st_mode))
652 out_dev = stat_buf.st_dev;
653 out_ino = stat_buf.st_ino;
657 check_redirection = false;
658 #ifdef lint /* Suppress `used before initialized' warning. */
664 if (! (number | show_ends | squeeze_blank))
666 file_open_mode |= O_BINARY;
667 if (O_BINARY && ! isatty (STDOUT_FILENO))
668 freopen (NULL, "wb", stdout);
671 /* Check if any of the input files are the same as the output file. */
681 infile = argv[argind];
683 if (STREQ (infile, "-"))
685 have_read_stdin = true;
686 input_desc = STDIN_FILENO;
687 if ((file_open_mode & O_BINARY) && ! isatty (STDIN_FILENO))
688 freopen (NULL, "rb", stdin);
692 input_desc = open (infile, file_open_mode);
695 error (0, errno, "%s", infile);
701 if (fstat (input_desc, &stat_buf) < 0)
703 error (0, errno, "%s", infile);
707 insize = ST_BLKSIZE (stat_buf);
709 /* Compare the device and i-node numbers of this input file with
710 the corresponding values of the (output file associated with)
711 stdout, and skip this input file if they coincide. Input
712 files cannot be redirected to themselves. */
714 if (check_redirection
715 && stat_buf.st_dev == out_dev && stat_buf.st_ino == out_ino
716 && (input_desc != STDIN_FILENO))
718 error (0, 0, _("%s: input file is output file"), infile);
723 /* Select which version of `cat' to use. If any format-oriented
724 options were given use `cat'; otherwise use `simple_cat'. */
726 if (! (number | show_ends | show_nonprinting
727 | show_tabs | squeeze_blank))
729 insize = max (insize, outsize);
730 inbuf = xmalloc (insize + page_size - 1);
732 ok &= simple_cat (ptr_align (inbuf, page_size), insize);
736 inbuf = xmalloc (insize + 1 + page_size - 1);
739 (OUTSIZE - 1 + INSIZE * 4 + LINE_COUNTER_BUF_LEN + PAGE_SIZE - 1)
740 bytes allocated for the output buffer?
742 A test whether output needs to be written is done when the input
743 buffer empties or when a newline appears in the input. After
744 output is written, at most (OUTSIZE - 1) bytes will remain in the
745 buffer. Now INSIZE bytes of input is read. Each input character
746 may grow by a factor of 4 (by the prepending of M-^). If all
747 characters do, and no newlines appear in this block of input, we
748 will have at most (OUTSIZE - 1 + INSIZE * 4) bytes in the buffer.
749 If the last character in the preceding block of input was a
750 newline, a line number may be written (according to the given
751 options) as the first thing in the output buffer. (Done after the
752 new input is read, but before processing of the input begins.)
753 A line number requires seldom more than LINE_COUNTER_BUF_LEN
756 Align the output buffer to a page size boundary, for efficency on
757 some paging implementations, so add PAGE_SIZE - 1 bytes to the
758 request to make room for the alignment. */
760 outbuf = xmalloc (outsize - 1 + insize * 4 + LINE_COUNTER_BUF_LEN
763 ok &= cat (ptr_align (inbuf, page_size), insize,
764 ptr_align (outbuf, page_size), outsize, show_nonprinting,
765 show_tabs, number, number_nonblank, show_ends,
774 if (!STREQ (infile, "-") && close (input_desc) < 0)
776 error (0, errno, "%s", infile);
780 while (++argind < argc);
782 if (have_read_stdin && close (STDIN_FILENO) < 0)
783 error (EXIT_FAILURE, errno, _("closing standard input"));
785 exit (ok ? EXIT_SUCCESS : EXIT_FAILURE);