*** empty log message ***
[coreutils.git] / src / cat.c
blob9587f78652ac88ff37658f8b3ca1ff4072c224b9
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)
7 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, 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. */
25 #include <config.h>
27 #include <stdio.h>
28 #include <getopt.h>
29 #include <sys/types.h>
30 #ifndef _POSIX_SOURCE
31 # include <sys/ioctl.h>
32 #endif
33 #include "system.h"
34 #include "closeout.h"
35 #include "error.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. */
44 #undef max
45 #define max(h,i) ((h) > (i) ? (h) : (i))
47 int full_write ();
49 /* Name under which this program was invoked. */
50 char *program_name;
52 /* Name of input file. May be "-". */
53 static char *infile;
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',
66 '\t', '\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;
85 void
86 usage (int status)
88 if (status != 0)
89 fprintf (stderr, _("Try `%s --help' for more information.\n"),
90 program_name);
91 else
93 printf (_("\
94 Usage: %s [OPTION] [FILE]...\n\
95 "),
96 program_name);
97 printf (_("\
98 Concatenate FILE(s), or standard input, to standard output.\n\
99 \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\
108 -u (ignored)\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\
114 "));
115 #if O_BINARY
116 printf (_("\
118 -B, --binary use binary writes to the console device.\n\n\
119 "));
120 #endif
121 puts (_("\nReport bugs to <bug-textutils@gnu.org>."));
123 exit (status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
126 /* Compute the next line number. */
128 static void
129 next_line_num (void)
131 char *endp = line_num_end;
134 if ((*endp)++ < '9')
135 return;
136 *endp-- = '0';
138 while (endp >= line_num_start);
139 if (line_num_start > line_buf)
140 *--line_num_start = '1';
141 else
142 *line_buf = '>';
143 if (line_num_start < line_num_print)
144 line_num_print--;
147 /* Plain cat. Copies the file behind `input_desc' to STDOUT_FILENO. */
149 static void
150 simple_cat (
151 /* Pointer to the buffer, used by reads and writes. */
152 unsigned char *buf,
154 /* Number of characters preferably read or written by each read and write
155 call. */
156 int bufsize)
158 /* Actual number of characters read, and therefore written. */
159 int n_read;
161 /* Loop until the end of the file. */
163 for (;;)
165 /* Read a block of input. */
167 n_read = safe_read (input_desc, buf, bufsize);
168 if (n_read < 0)
170 error (0, errno, "%s", infile);
171 exit_status = 1;
172 return;
175 /* End of this file? */
177 if (n_read == 0)
178 break;
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. */
193 static void
194 cat (
195 /* Pointer to the beginning of the input buffer. */
196 unsigned char *inbuf,
198 /* Number of characters read in each read call. */
199 int insize,
201 /* Pointer to the beginning of the output buffer. */
202 unsigned char *outbuf,
204 /* Number of characters written by each write call. */
205 int outsize,
207 /* Variables that have values according to the specified options. */
208 int quote,
209 int output_tabs,
210 int numbers,
211 int numbers_at_empty_lines,
212 int mark_line_ends,
213 int squeeze_empty_lines)
215 /* Last character read from the input buffer. */
216 unsigned char ch;
218 /* Pointer to the next character in the input buffer. */
219 unsigned char *bpin;
221 /* Pointer to the first non-valid byte in the input buffer, i.e. the
222 current end of the buffer. */
223 unsigned char *eob;
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. */
229 int n_read;
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
235 NEWLINES. */
236 int newlines = newlines2;
238 #ifdef FIONREAD
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;
242 #endif
244 /* The inbuf pointers are initialized so that BPIN > EOB, and thereby input
245 is read immediately. */
247 eob = inbuf;
248 bpin = eob + 1;
250 bpout = outbuf;
252 for (;;)
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"));
265 wp += outsize;
267 while (bpout - wp >= outsize);
269 /* Move the remaining bytes to the beginning of the
270 buffer. */
272 memmove (outbuf, wp, bpout - wp);
273 bpout = outbuf + (bpout - wp);
276 /* Is INBUF empty? */
278 if (bpin > eob)
280 #ifdef FIONREAD
281 int n_to_read = 0;
283 /* Is there any input to read immediately?
284 If not, we are about to wait,
285 so write all buffered output before waiting. */
287 if (use_fionread
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
294 like /dev/null.
295 Irix-5 returns ENOSYS on pipes. */
296 if (errno == EOPNOTSUPP || errno == ENOTTY
297 || errno == EINVAL || errno == ENODEV
298 # ifdef ENOSYS
299 || errno == ENOSYS
300 # endif
302 use_fionread = 0;
303 else
305 error (0, errno, _("cannot do ioctl on `%s'"), infile);
306 exit_status = 1;
307 newlines2 = newlines;
308 return;
311 if (n_to_read == 0)
312 #endif
314 int n_write = bpout - outbuf;
316 if (full_write (STDOUT_FILENO, outbuf, n_write) < 0)
317 error (EXIT_FAILURE, errno, _("write error"));
318 bpout = outbuf;
321 /* Read more input into INBUF. */
323 n_read = safe_read (input_desc, inbuf, insize);
324 if (n_read < 0)
326 error (0, errno, "%s", infile);
327 exit_status = 1;
328 newlines2 = newlines;
329 return;
331 if (n_read == 0)
333 newlines2 = newlines;
334 return;
337 /* Update the pointers and insert a sentinel at the buffer
338 end. */
340 bpin = inbuf;
341 eob = bpin + n_read;
342 *eob = '\n';
344 else
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?) */
351 if (++newlines > 0)
353 if (newlines >= 2)
355 /* Limit this to 2 here. Otherwise, with lots of
356 consecutive newlines, the counter could wrap
357 around at INT_MAX. */
358 newlines = 2;
360 /* Are multiple adjacent empty lines to be substituted
361 by single ditto (-s), and this was the second empty
362 line? */
363 if (squeeze_empty_lines)
365 ch = *bpin++;
366 continue;
370 /* Are line numbers to be written at empty lines (-n)? */
372 if (numbers && numbers_at_empty_lines)
374 next_line_num ();
375 bpout = (unsigned char *) stpcpy ((char *) bpout,
376 line_num_print);
380 /* Output a currency symbol if requested (-e). */
382 if (mark_line_ends)
383 *bpout++ = '$';
385 /* Output the newline. */
387 *bpout++ = '\n';
389 ch = *bpin++;
391 while (ch == '\n');
393 /* Are we at the beginning of a line, and line numbers are requested? */
395 if (newlines >= 0 && numbers)
397 next_line_num ();
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
405 has been found. */
407 /* If quoting, i.e. at least one of -v, -e, or -t specified,
408 scan for chars that need conversion. */
409 if (quote)
411 for (;;)
413 if (ch >= 32)
415 if (ch < 127)
416 *bpout++ = ch;
417 else if (ch == 127)
419 *bpout++ = '^';
420 *bpout++ = '?';
422 else
424 *bpout++ = 'M';
425 *bpout++ = '-';
426 if (ch >= 128 + 32)
428 if (ch < 128 + 127)
429 *bpout++ = ch - 128;
430 else
432 *bpout++ = '^';
433 *bpout++ = '?';
436 else
438 *bpout++ = '^';
439 *bpout++ = ch - 128 + 64;
443 else if (ch == '\t' && output_tabs)
444 *bpout++ = '\t';
445 else if (ch == '\n')
447 newlines = -1;
448 break;
450 else
452 *bpout++ = '^';
453 *bpout++ = ch + 64;
456 ch = *bpin++;
459 else
461 /* Not quoting, neither of -v, -e, or -t specified. */
462 for (;;)
464 if (ch == '\t' && !output_tabs)
466 *bpout++ = '^';
467 *bpout++ = ch + 64;
469 else if (ch != '\n')
470 *bpout++ = ch;
471 else
473 newlines = -1;
474 break;
477 ch = *bpin++;
484 main (int argc, char **argv)
486 /* Optimal size of i/o operations of output. */
487 int outsize;
489 /* Optimal size of i/o operations of input. */
490 int insize;
492 /* Pointer to the input buffer. */
493 unsigned char *inbuf;
495 /* Pointer to the output buffer. */
496 unsigned char *outbuf;
498 int c;
500 /* Index in argv to processed argument. */
501 int argind;
503 /* Device number of the output (file or whatever). */
504 dev_t out_dev;
506 /* I-node number of the output. */
507 ino_t out_ino;
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. */
518 int numbers = 0;
519 int numbers_at_empty_lines = 1;
520 int squeeze_empty_lines = 0;
521 int mark_line_ends = 0;
522 int quote = 0;
523 int output_tabs = 1;
524 #if O_BINARY
525 int binary_files = 0;
526 int binary_output = 0;
527 #endif
528 int file_open_mode = O_RDONLY;
530 /* If nonzero, call cat, otherwise call simple_cat to do the actual work. */
531 int options = 0;
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'},
542 #if O_BINARY
543 {"binary", no_argument, NULL, 'B'},
544 #endif
545 {GETOPT_HELP_OPTION_DECL},
546 {GETOPT_VERSION_OPTION_DECL},
547 {NULL, 0, NULL, 0}
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,
560 #if O_BINARY
561 "benstuvABET"
562 #else
563 "benstuvAET"
564 #endif
565 , long_options, NULL)) != -1)
567 switch (c)
569 case 0:
570 break;
572 case 'b':
573 ++options;
574 numbers = 1;
575 numbers_at_empty_lines = 0;
576 break;
578 case 'e':
579 ++options;
580 mark_line_ends = 1;
581 quote = 1;
582 break;
584 case 'n':
585 ++options;
586 numbers = 1;
587 break;
589 case 's':
590 ++options;
591 squeeze_empty_lines = 1;
592 break;
594 case 't':
595 ++options;
596 output_tabs = 0;
597 quote = 1;
598 break;
600 case 'u':
601 /* We provide the -u feature unconditionally. */
602 break;
604 case 'v':
605 ++options;
606 quote = 1;
607 break;
609 case 'A':
610 ++options;
611 quote = 1;
612 mark_line_ends = 1;
613 output_tabs = 0;
614 break;
616 #if O_BINARY
617 case 'B':
618 ++options;
619 binary_files = 1;
620 break;
621 #endif
623 case 'E':
624 ++options;
625 mark_line_ends = 1;
626 break;
628 case 'T':
629 ++options;
630 output_tabs = 0;
631 break;
633 case_GETOPT_HELP_CHAR;
635 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
637 default:
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;
659 else
661 check_redirection = 0;
662 #ifdef lint /* Suppress `used before initialized' warning. */
663 out_dev = 0;
664 out_ino = 0;
665 #endif
668 #if O_BINARY
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))
679 || binary_files)
681 /* Switch stdout to BINARY mode. */
682 binary_output = 1;
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;
688 else if (quote)
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;
695 SET_BINARY (0);
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);
702 #endif
704 /* Check if any of the input files are the same as the output file. */
706 /* Main loop. */
708 infile = "-";
709 argind = optind;
713 if (argind < argc)
714 infile = argv[argind];
716 if (infile[0] == '-' && infile[1] == 0)
718 have_read_stdin = 1;
719 input_desc = 0;
721 #if O_BINARY
722 /* Switch stdin to BINARY mode if needed. */
723 if (binary_output)
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);
734 else
736 SET_BINARY (input_desc);
737 # ifdef __DJGPP__
738 /* This is DJGPP-specific. By default, switching console
739 to binary mode disables SIGINT. But we want terminal
740 reads to be interruptible. */
741 if (tty_in)
742 __djgpp_set_ctrl_c (1);
743 # endif
746 #endif
748 else
750 input_desc = open (infile, file_open_mode);
751 if (input_desc < 0)
753 error (0, errno, "%s", infile);
754 exit_status = 1;
755 continue;
759 if (fstat (input_desc, &stat_buf) < 0)
761 error (0, errno, "%s", infile);
762 exit_status = 1;
763 goto contin;
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);
777 exit_status = 1;
778 goto contin;
781 /* Select which version of `cat' to use. If any options (more than -u,
782 --version, or --help) were specified, use `cat', otherwise use
783 `simple_cat'. */
785 if (options == 0)
787 insize = max (insize, outsize);
788 inbuf = (unsigned char *) xmalloc (insize);
790 simple_cat (inbuf, insize);
792 else
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
811 positions. */
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);
820 free (outbuf);
823 free (inbuf);
825 contin:
826 if (!STREQ (infile, "-") && close (input_desc) < 0)
828 error (0, errno, "%s", infile);
829 exit_status = 1;
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);