*** empty log message ***
[coreutils.git] / src / cat.c
blob8fe48e648401c91d24d978c28fb22fc21d7fcd31
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)
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 /* Undefine, to avoid warning about redefinition on some systems. */
38 #undef max
39 #define max(h,i) ((h) > (i) ? (h) : (i))
41 int full_write ();
43 /* Name under which this program was invoked. */
44 char *program_name;
46 /* Name of input file. May be "-". */
47 static char *infile;
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;
75 void
76 usage (int status)
78 if (status != 0)
79 fprintf (stderr, _("Try `%s --help' for more information.\n"),
80 program_name);
81 else
83 printf (_("\
84 Usage: %s [OPTION] [FILE]...\n\
85 "),
86 program_name);
87 printf (_("\
88 Concatenate FILE(s), or standard input, to standard output.\n\
89 \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\
98 -u (ignored)\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\
104 "));
105 #if O_BINARY
106 printf (_("\
108 -B, --binary use binary writes to the console device.\n\n\
109 "));
110 #endif
111 puts (_("\nReport bugs to <bug-textutils@gnu.org>."));
113 exit (status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
116 /* Compute the next line number. */
118 static void
119 next_line_num (void)
121 char *endp = line_num_end;
124 if ((*endp)++ < '9')
125 return;
126 *endp-- = '0';
128 while (endp >= line_num_start);
129 *--line_num_start = '1';
130 if (line_num_start < line_num_print)
131 line_num_print--;
134 /* Plain cat. Copies the file behind `input_desc' to the file behind
135 `output_desc'. */
137 static void
138 simple_cat (
139 /* Pointer to the buffer, used by reads and writes. */
140 unsigned char *buf,
142 /* Number of characters preferably read or written by each read and write
143 call. */
144 int bufsize)
146 /* Actual number of characters read, and therefore written. */
147 int n_read;
149 /* Loop until the end of the file. */
151 for (;;)
153 /* Read a block of input. */
155 n_read = safe_read (input_desc, buf, bufsize);
156 if (n_read < 0)
158 error (0, errno, "%s", infile);
159 exit_status = 1;
160 return;
163 /* End of this file? */
165 if (n_read == 0)
166 break;
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. */
181 static void
182 cat (
183 /* Pointer to the beginning of the input buffer. */
184 unsigned char *inbuf,
186 /* Number of characters read in each read call. */
187 int insize,
189 /* Pointer to the beginning of the output buffer. */
190 unsigned char *outbuf,
192 /* Number of characters written by each write call. */
193 int outsize,
195 /* Variables that have values according to the specified options. */
196 int quote,
197 int output_tabs,
198 int numbers,
199 int numbers_at_empty_lines,
200 int mark_line_ends,
201 int squeeze_empty_lines)
203 /* Last character read from the input buffer. */
204 unsigned char ch;
206 /* Pointer to the next character in the input buffer. */
207 unsigned char *bpin;
209 /* Pointer to the first non-valid byte in the input buffer, i.e. the
210 current end of the buffer. */
211 unsigned char *eob;
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. */
217 int n_read;
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
223 NEWLINES. */
224 int newlines = newlines2;
226 #ifdef FIONREAD
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;
230 #endif
232 /* The inbuf pointers are initialized so that BPIN > EOB, and thereby input
233 is read immediately. */
235 eob = inbuf;
236 bpin = eob + 1;
238 bpout = outbuf;
240 for (;;)
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"));
253 wp += outsize;
255 while (bpout - wp >= outsize);
257 /* Move the remaining bytes to the beginning of the
258 buffer. */
260 memmove (outbuf, wp, bpout - wp);
261 bpout = outbuf + (bpout - wp);
264 /* Is INBUF empty? */
266 if (bpin > eob)
268 #ifdef FIONREAD
269 int n_to_read = 0;
271 /* Is there any input to read immediately?
272 If not, we are about to wait,
273 so write all buffered output before waiting. */
275 if (use_fionread
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
282 like /dev/null.
283 Irix-5 returns ENOSYS on pipes. */
284 if (errno == EOPNOTSUPP || errno == ENOTTY
285 || errno == EINVAL || errno == ENODEV
286 # ifdef ENOSYS
287 || errno == ENOSYS
288 # endif
290 use_fionread = 0;
291 else
293 error (0, errno, _("cannot do ioctl on `%s'"), infile);
294 exit_status = 1;
295 newlines2 = newlines;
296 return;
299 if (n_to_read == 0)
300 #endif
302 int n_write = bpout - outbuf;
304 if (full_write (output_desc, outbuf, n_write) < 0)
305 error (EXIT_FAILURE, errno, _("write error"));
306 bpout = outbuf;
309 /* Read more input into INBUF. */
311 n_read = safe_read (input_desc, inbuf, insize);
312 if (n_read < 0)
314 error (0, errno, "%s", infile);
315 exit_status = 1;
316 newlines2 = newlines;
317 return;
319 if (n_read == 0)
321 newlines2 = newlines;
322 return;
325 /* Update the pointers and insert a sentinel at the buffer
326 end. */
328 bpin = inbuf;
329 eob = bpin + n_read;
330 *eob = '\n';
332 else
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?) */
339 if (++newlines > 0)
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)
346 ch = *bpin++;
347 continue;
350 /* Are line numbers to be written at empty lines (-n)? */
352 if (numbers && numbers_at_empty_lines)
354 next_line_num ();
355 bpout = (unsigned char *) stpcpy ((char *) bpout,
356 line_num_print);
360 /* Output a currency symbol if requested (-e). */
362 if (mark_line_ends)
363 *bpout++ = '$';
365 /* Output the newline. */
367 *bpout++ = '\n';
369 ch = *bpin++;
371 while (ch == '\n');
373 /* Are we at the beginning of a line, and line numbers are requested? */
375 if (newlines >= 0 && numbers)
377 next_line_num ();
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
385 has been found. */
387 /* If quoting, i.e. at least one of -v, -e, or -t specified,
388 scan for chars that need conversion. */
389 if (quote)
391 for (;;)
393 if (ch >= 32)
395 if (ch < 127)
396 *bpout++ = ch;
397 else if (ch == 127)
399 *bpout++ = '^';
400 *bpout++ = '?';
402 else
404 *bpout++ = 'M';
405 *bpout++ = '-';
406 if (ch >= 128 + 32)
408 if (ch < 128 + 127)
409 *bpout++ = ch - 128;
410 else
412 *bpout++ = '^';
413 *bpout++ = '?';
416 else
418 *bpout++ = '^';
419 *bpout++ = ch - 128 + 64;
423 else if (ch == '\t' && output_tabs)
424 *bpout++ = '\t';
425 else if (ch == '\n')
427 newlines = -1;
428 break;
430 else
432 *bpout++ = '^';
433 *bpout++ = ch + 64;
436 ch = *bpin++;
439 else
441 /* Not quoting, neither of -v, -e, or -t specified. */
442 for (;;)
444 if (ch == '\t' && !output_tabs)
446 *bpout++ = '^';
447 *bpout++ = ch + 64;
449 else if (ch != '\n')
450 *bpout++ = ch;
451 else
453 newlines = -1;
454 break;
457 ch = *bpin++;
464 main (int argc, char **argv)
466 /* Optimal size of i/o operations of output. */
467 int outsize;
469 /* Optimal size of i/o operations of input. */
470 int insize;
472 /* Pointer to the input buffer. */
473 unsigned char *inbuf;
475 /* Pointer to the output buffer. */
476 unsigned char *outbuf;
478 int c;
480 /* Index in argv to processed argument. */
481 int argind;
483 /* Device number of the output (file or whatever). */
484 int out_dev;
486 /* I-node number of the output. */
487 int out_ino;
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. */
498 int numbers = 0;
499 int numbers_at_empty_lines = 1;
500 int squeeze_empty_lines = 0;
501 int mark_line_ends = 0;
502 int quote = 0;
503 int output_tabs = 1;
504 #if O_BINARY
505 int binary_files = 0;
506 int binary_output = 0;
507 #endif
508 int file_open_mode = O_RDONLY;
510 /* If nonzero, call cat, otherwise call simple_cat to do the actual work. */
511 int options = 0;
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'},
528 #if O_BINARY
529 {"binary", no_argument, NULL, 'B'},
530 #endif
531 {"help", no_argument, &show_help, 1},
532 {"version", no_argument, &show_version, 1},
533 {NULL, 0, NULL, 0}
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,
544 #if O_BINARY
545 "benstuvABET"
546 #else
547 "benstuvAET"
548 #endif
549 , long_options, NULL)) != -1)
551 switch (c)
553 case 0:
554 break;
556 case 'b':
557 ++options;
558 numbers = 1;
559 numbers_at_empty_lines = 0;
560 break;
562 case 'e':
563 ++options;
564 mark_line_ends = 1;
565 quote = 1;
566 break;
568 case 'n':
569 ++options;
570 numbers = 1;
571 break;
573 case 's':
574 ++options;
575 squeeze_empty_lines = 1;
576 break;
578 case 't':
579 ++options;
580 output_tabs = 0;
581 quote = 1;
582 break;
584 case 'u':
585 /* We provide the -u feature unconditionally. */
586 break;
588 case 'v':
589 ++options;
590 quote = 1;
591 break;
593 case 'A':
594 ++options;
595 quote = 1;
596 mark_line_ends = 1;
597 output_tabs = 0;
598 break;
600 #if O_BINARY
601 case 'B':
602 ++options;
603 binary_files = 1;
604 break;
605 #endif
607 case 'E':
608 ++options;
609 mark_line_ends = 1;
610 break;
612 case 'T':
613 ++options;
614 output_tabs = 0;
615 break;
617 default:
618 usage (EXIT_FAILURE);
622 if (show_version)
624 printf ("cat (%s) %s\n", GNU_PACKAGE, VERSION);
625 exit (EXIT_SUCCESS);
628 if (show_help)
629 usage (0);
631 output_desc = 1;
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;
650 else
652 check_redirection = 0;
653 #ifdef lint /* Suppress `used before initialized' warning. */
654 out_dev = 0;
655 out_ino = 0;
656 #endif
659 #if O_BINARY
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))
670 || binary_files)
672 /* Switch stdout to BINARY mode. */
673 binary_output = 1;
674 SET_BINARY (output_desc);
676 else if (quote)
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;
683 SET_BINARY (0);
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);
690 #endif
692 /* Check if any of the input files are the same as the output file. */
694 /* Main loop. */
696 infile = "-";
697 argind = optind;
701 if (argind < argc)
702 infile = argv[argind];
704 if (infile[0] == '-' && infile[1] == 0)
706 have_read_stdin = 1;
707 input_desc = 0;
709 #if O_BINARY
710 /* Switch stdin to BINARY mode if needed. */
711 if (binary_output)
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);
722 else
724 SET_BINARY (input_desc);
725 # ifdef __DJGPP__
726 /* This is DJGPP-specific. By default, switching console
727 to binary mode disables SIGINT. But we want terminal
728 reads to be interruptible. */
729 if (tty_in)
730 __djgpp_set_ctrl_c (1);
731 # endif
734 #endif
736 else
738 input_desc = open (infile, file_open_mode);
739 if (input_desc < 0)
741 error (0, errno, "%s", infile);
742 exit_status = 1;
743 continue;
747 if (fstat (input_desc, &stat_buf) < 0)
749 error (0, errno, "%s", infile);
750 exit_status = 1;
751 goto contin;
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);
765 exit_status = 1;
766 goto contin;
769 /* Select which version of `cat' to use. If any options (more than -u,
770 --version, or --help) were specified, use `cat', otherwise use
771 `simple_cat'. */
773 if (options == 0)
775 insize = max (insize, outsize);
776 inbuf = (unsigned char *) xmalloc (insize);
778 simple_cat (inbuf, insize);
780 else
782 inbuf = (unsigned char *) xmalloc (insize + 1);
784 /* Why are (OUTSIZE - 1 + INSIZE * 4 + 13) bytes allocated for
785 the output buffer?
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);
806 free (outbuf);
809 free (inbuf);
811 contin:
812 if (!STREQ (infile, "-") && close (input_desc) < 0)
814 error (0, errno, "%s", infile);
815 exit_status = 1;
818 while (++argind < argc);
820 if (have_read_stdin && close (0) < 0)
821 error (EXIT_FAILURE, errno, "-");
822 if (close (1) < 0)
823 error (EXIT_FAILURE, errno, _("write error"));
825 exit (exit_status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);