*** empty log message ***
[coreutils.git] / src / cat.c
blob37f47c96760942dea7948d91262fec755c69c32e
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)
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 "error.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. */
43 #undef max
44 #define max(h,i) ((h) > (i) ? (h) : (i))
46 int full_write ();
48 /* Name under which this program was invoked. */
49 char *program_name;
51 /* Name of input file. May be "-". */
52 static char *infile;
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;
80 void
81 usage (int status)
83 if (status != 0)
84 fprintf (stderr, _("Try `%s --help' for more information.\n"),
85 program_name);
86 else
88 printf (_("\
89 Usage: %s [OPTION] [FILE]...\n\
90 "),
91 program_name);
92 printf (_("\
93 Concatenate FILE(s), or standard input, to standard output.\n\
94 \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\
103 -u (ignored)\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\
109 "));
110 #if O_BINARY
111 printf (_("\
113 -B, --binary use binary writes to the console device.\n\n\
114 "));
115 #endif
116 puts (_("\nReport bugs to <bug-textutils@gnu.org>."));
118 exit (status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
121 /* Compute the next line number. */
123 static void
124 next_line_num (void)
126 char *endp = line_num_end;
129 if ((*endp)++ < '9')
130 return;
131 *endp-- = '0';
133 while (endp >= line_num_start);
134 *--line_num_start = '1';
135 if (line_num_start < line_num_print)
136 line_num_print--;
139 /* Plain cat. Copies the file behind `input_desc' to the file behind
140 `output_desc'. */
142 static void
143 simple_cat (
144 /* Pointer to the buffer, used by reads and writes. */
145 unsigned char *buf,
147 /* Number of characters preferably read or written by each read and write
148 call. */
149 int bufsize)
151 /* Actual number of characters read, and therefore written. */
152 int n_read;
154 /* Loop until the end of the file. */
156 for (;;)
158 /* Read a block of input. */
160 n_read = safe_read (input_desc, buf, bufsize);
161 if (n_read < 0)
163 error (0, errno, "%s", infile);
164 exit_status = 1;
165 return;
168 /* End of this file? */
170 if (n_read == 0)
171 break;
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. */
186 static void
187 cat (
188 /* Pointer to the beginning of the input buffer. */
189 unsigned char *inbuf,
191 /* Number of characters read in each read call. */
192 int insize,
194 /* Pointer to the beginning of the output buffer. */
195 unsigned char *outbuf,
197 /* Number of characters written by each write call. */
198 int outsize,
200 /* Variables that have values according to the specified options. */
201 int quote,
202 int output_tabs,
203 int numbers,
204 int numbers_at_empty_lines,
205 int mark_line_ends,
206 int squeeze_empty_lines)
208 /* Last character read from the input buffer. */
209 unsigned char ch;
211 /* Pointer to the next character in the input buffer. */
212 unsigned char *bpin;
214 /* Pointer to the first non-valid byte in the input buffer, i.e. the
215 current end of the buffer. */
216 unsigned char *eob;
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. */
222 int n_read;
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
228 NEWLINES. */
229 int newlines = newlines2;
231 #ifdef FIONREAD
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;
235 #endif
237 /* The inbuf pointers are initialized so that BPIN > EOB, and thereby input
238 is read immediately. */
240 eob = inbuf;
241 bpin = eob + 1;
243 bpout = outbuf;
245 for (;;)
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"));
258 wp += outsize;
260 while (bpout - wp >= outsize);
262 /* Move the remaining bytes to the beginning of the
263 buffer. */
265 memmove (outbuf, wp, bpout - wp);
266 bpout = outbuf + (bpout - wp);
269 /* Is INBUF empty? */
271 if (bpin > eob)
273 #ifdef FIONREAD
274 int n_to_read = 0;
276 /* Is there any input to read immediately?
277 If not, we are about to wait,
278 so write all buffered output before waiting. */
280 if (use_fionread
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
287 like /dev/null.
288 Irix-5 returns ENOSYS on pipes. */
289 if (errno == EOPNOTSUPP || errno == ENOTTY
290 || errno == EINVAL || errno == ENODEV
291 # ifdef ENOSYS
292 || errno == ENOSYS
293 # endif
295 use_fionread = 0;
296 else
298 error (0, errno, _("cannot do ioctl on `%s'"), infile);
299 exit_status = 1;
300 newlines2 = newlines;
301 return;
304 if (n_to_read == 0)
305 #endif
307 int n_write = bpout - outbuf;
309 if (full_write (output_desc, outbuf, n_write) < 0)
310 error (EXIT_FAILURE, errno, _("write error"));
311 bpout = outbuf;
314 /* Read more input into INBUF. */
316 n_read = safe_read (input_desc, inbuf, insize);
317 if (n_read < 0)
319 error (0, errno, "%s", infile);
320 exit_status = 1;
321 newlines2 = newlines;
322 return;
324 if (n_read == 0)
326 newlines2 = newlines;
327 return;
330 /* Update the pointers and insert a sentinel at the buffer
331 end. */
333 bpin = inbuf;
334 eob = bpin + n_read;
335 *eob = '\n';
337 else
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?) */
344 if (++newlines > 0)
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)
351 ch = *bpin++;
352 continue;
355 /* Are line numbers to be written at empty lines (-n)? */
357 if (numbers && numbers_at_empty_lines)
359 next_line_num ();
360 bpout = (unsigned char *) stpcpy ((char *) bpout,
361 line_num_print);
365 /* Output a currency symbol if requested (-e). */
367 if (mark_line_ends)
368 *bpout++ = '$';
370 /* Output the newline. */
372 *bpout++ = '\n';
374 ch = *bpin++;
376 while (ch == '\n');
378 /* Are we at the beginning of a line, and line numbers are requested? */
380 if (newlines >= 0 && numbers)
382 next_line_num ();
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
390 has been found. */
392 /* If quoting, i.e. at least one of -v, -e, or -t specified,
393 scan for chars that need conversion. */
394 if (quote)
396 for (;;)
398 if (ch >= 32)
400 if (ch < 127)
401 *bpout++ = ch;
402 else if (ch == 127)
404 *bpout++ = '^';
405 *bpout++ = '?';
407 else
409 *bpout++ = 'M';
410 *bpout++ = '-';
411 if (ch >= 128 + 32)
413 if (ch < 128 + 127)
414 *bpout++ = ch - 128;
415 else
417 *bpout++ = '^';
418 *bpout++ = '?';
421 else
423 *bpout++ = '^';
424 *bpout++ = ch - 128 + 64;
428 else if (ch == '\t' && output_tabs)
429 *bpout++ = '\t';
430 else if (ch == '\n')
432 newlines = -1;
433 break;
435 else
437 *bpout++ = '^';
438 *bpout++ = ch + 64;
441 ch = *bpin++;
444 else
446 /* Not quoting, neither of -v, -e, or -t specified. */
447 for (;;)
449 if (ch == '\t' && !output_tabs)
451 *bpout++ = '^';
452 *bpout++ = ch + 64;
454 else if (ch != '\n')
455 *bpout++ = ch;
456 else
458 newlines = -1;
459 break;
462 ch = *bpin++;
469 main (int argc, char **argv)
471 /* Optimal size of i/o operations of output. */
472 int outsize;
474 /* Optimal size of i/o operations of input. */
475 int insize;
477 /* Pointer to the input buffer. */
478 unsigned char *inbuf;
480 /* Pointer to the output buffer. */
481 unsigned char *outbuf;
483 int c;
485 /* Index in argv to processed argument. */
486 int argind;
488 /* Device number of the output (file or whatever). */
489 dev_t out_dev;
491 /* I-node number of the output. */
492 ino_t out_ino;
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. */
503 int numbers = 0;
504 int numbers_at_empty_lines = 1;
505 int squeeze_empty_lines = 0;
506 int mark_line_ends = 0;
507 int quote = 0;
508 int output_tabs = 1;
509 #if O_BINARY
510 int binary_files = 0;
511 int binary_output = 0;
512 #endif
513 int file_open_mode = O_RDONLY;
515 /* If nonzero, call cat, otherwise call simple_cat to do the actual work. */
516 int options = 0;
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'},
527 #if O_BINARY
528 {"binary", no_argument, NULL, 'B'},
529 #endif
530 {GETOPT_HELP_OPTION_DECL},
531 {GETOPT_VERSION_OPTION_DECL},
532 {NULL, 0, NULL, 0}
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,
543 #if O_BINARY
544 "benstuvABET"
545 #else
546 "benstuvAET"
547 #endif
548 , long_options, NULL)) != -1)
550 switch (c)
552 case 0:
553 break;
555 case 'b':
556 ++options;
557 numbers = 1;
558 numbers_at_empty_lines = 0;
559 break;
561 case 'e':
562 ++options;
563 mark_line_ends = 1;
564 quote = 1;
565 break;
567 case 'n':
568 ++options;
569 numbers = 1;
570 break;
572 case 's':
573 ++options;
574 squeeze_empty_lines = 1;
575 break;
577 case 't':
578 ++options;
579 output_tabs = 0;
580 quote = 1;
581 break;
583 case 'u':
584 /* We provide the -u feature unconditionally. */
585 break;
587 case 'v':
588 ++options;
589 quote = 1;
590 break;
592 case 'A':
593 ++options;
594 quote = 1;
595 mark_line_ends = 1;
596 output_tabs = 0;
597 break;
599 #if O_BINARY
600 case 'B':
601 ++options;
602 binary_files = 1;
603 break;
604 #endif
606 case 'E':
607 ++options;
608 mark_line_ends = 1;
609 break;
611 case 'T':
612 ++options;
613 output_tabs = 0;
614 break;
616 case_GETOPT_HELP_CHAR;
618 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
620 default:
621 usage (EXIT_FAILURE);
625 output_desc = 1;
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;
644 else
646 check_redirection = 0;
647 #ifdef lint /* Suppress `used before initialized' warning. */
648 out_dev = 0;
649 out_ino = 0;
650 #endif
653 #if O_BINARY
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))
664 || binary_files)
666 /* Switch stdout to BINARY mode. */
667 binary_output = 1;
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;
673 else if (quote)
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;
680 SET_BINARY (0);
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);
687 #endif
689 /* Check if any of the input files are the same as the output file. */
691 /* Main loop. */
693 infile = "-";
694 argind = optind;
698 if (argind < argc)
699 infile = argv[argind];
701 if (infile[0] == '-' && infile[1] == 0)
703 have_read_stdin = 1;
704 input_desc = 0;
706 #if O_BINARY
707 /* Switch stdin to BINARY mode if needed. */
708 if (binary_output)
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);
719 else
721 SET_BINARY (input_desc);
722 # ifdef __DJGPP__
723 /* This is DJGPP-specific. By default, switching console
724 to binary mode disables SIGINT. But we want terminal
725 reads to be interruptible. */
726 if (tty_in)
727 __djgpp_set_ctrl_c (1);
728 # endif
731 #endif
733 else
735 input_desc = open (infile, file_open_mode);
736 if (input_desc < 0)
738 error (0, errno, "%s", infile);
739 exit_status = 1;
740 continue;
744 if (fstat (input_desc, &stat_buf) < 0)
746 error (0, errno, "%s", infile);
747 exit_status = 1;
748 goto contin;
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);
762 exit_status = 1;
763 goto contin;
766 /* Select which version of `cat' to use. If any options (more than -u,
767 --version, or --help) were specified, use `cat', otherwise use
768 `simple_cat'. */
770 if (options == 0)
772 insize = max (insize, outsize);
773 inbuf = (unsigned char *) xmalloc (insize);
775 simple_cat (inbuf, insize);
777 else
779 inbuf = (unsigned char *) xmalloc (insize + 1);
781 /* Why are (OUTSIZE - 1 + INSIZE * 4 + 13) bytes allocated for
782 the output buffer?
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);
803 free (outbuf);
806 free (inbuf);
808 contin:
809 if (!STREQ (infile, "-") && close (input_desc) < 0)
811 error (0, errno, "%s", infile);
812 exit_status = 1;
815 while (++argind < argc);
817 if (have_read_stdin && close (0) < 0)
818 error (EXIT_FAILURE, errno, "-");
819 if (close (1) < 0)
820 error (EXIT_FAILURE, errno, _("write error"));
822 exit (exit_status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);