.
[coreutils.git] / src / cat.c
blobd09be30de905dccc2572797b88522e1b0500b335
1 /* cat -- concatenate files and print on the standard output.
2 Copyright (C) 1988, 1990, 1991, 1995 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 "version.h"
35 #include "error.h"
37 /* Undefine, to avoid warning about redefinition on some systems. */
38 #undef max
39 #define max(h,i) ((h) > (i) ? (h) : (i))
41 char *stpcpy ();
42 char *xmalloc ();
43 int full_write ();
44 int safe_read ();
46 /* Name under which this program was invoked. */
47 char *program_name;
49 /* Name of input file. May be "-". */
50 static char *infile;
52 /* Descriptor on which input file is open. */
53 static int input_desc;
55 /* Descriptor on which output file is open. Always is 1. */
56 static int output_desc;
58 /* Buffer for line numbers. */
59 static char line_buf[13] =
60 {' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '0', '\t', '\0'};
62 /* Position in `line_buf' where printing starts. This will not change
63 unless the number of lines is larger than 999999. */
64 static char *line_num_print = line_buf + 5;
66 /* Position of the first digit in `line_buf'. */
67 static char *line_num_start = line_buf + 10;
69 /* Position of the last digit in `line_buf'. */
70 static char *line_num_end = line_buf + 10;
72 /* Preserves the `cat' function's local `newlines' between invocations. */
73 static int newlines2 = 0;
75 /* Count of non-fatal error conditions. */
76 static int exit_stat = 0;
78 static void
79 usage (int status)
81 if (status != 0)
82 fprintf (stderr, _("Try `%s --help' for more information.\n"),
83 program_name);
84 else
86 printf (_("\
87 Usage: %s [OPTION] [FILE]...\n\
88 "),
89 program_name);
90 printf (_("\
91 Concatenate FILE(s), or standard input, to standard output.\n\
92 \n\
93 -b, --number-nonblank number nonblank output lines\n\
94 -e equivalent to -vE\n\
95 -n, --number number all output lines\n\
96 -s, --squeeze-blank never more than one single blank line\n\
97 -t equivalent to -vT\n\
98 -u (ignored)\n\
99 -v, --show-nonprinting use ^ and M- notation, save for LFD and TAB\n\
100 -A, --show-all equivalent to -vET\n\
101 -E, --show-ends display $ at end of each line\n\
102 -T, --show-tabs display TAB characters as ^I\n\
103 --help display this help and exit\n\
104 --version output version information and exit\n\
106 With no FILE, or when FILE is -, read standard input.\n\
107 "));
109 exit (status);
112 /* Compute the next line number. */
114 static void
115 next_line_num (void)
117 char *endp = line_num_end;
120 if ((*endp)++ < '9')
121 return;
122 *endp-- = '0';
124 while (endp >= line_num_start);
125 *--line_num_start = '1';
126 if (line_num_start < line_num_print)
127 line_num_print--;
130 /* Plain cat. Copies the file behind `input_desc' to the file behind
131 `output_desc'. */
133 static void
134 simple_cat (
135 /* Pointer to the buffer, used by reads and writes. */
136 unsigned char *buf,
138 /* Number of characters preferably read or written by each read and write
139 call. */
140 int bufsize)
142 /* Actual number of characters read, and therefore written. */
143 int n_read;
145 /* Loop until the end of the file. */
147 for (;;)
149 /* Read a block of input. */
151 n_read = safe_read (input_desc, buf, bufsize);
152 if (n_read < 0)
154 error (0, errno, "%s", infile);
155 exit_stat = 1;
156 return;
159 /* End of this file? */
161 if (n_read == 0)
162 break;
164 /* Write this block out. */
166 if (full_write (output_desc, buf, n_read) < 0)
167 error (1, errno, _("write error"));
171 /* Cat the file behind INPUT_DESC to the file behind OUTPUT_DESC.
172 Called if any option more than -u was specified.
174 A newline character is always put at the end of the buffer, to make
175 an explicit test for buffer end unnecessary. */
177 static void
178 cat (
179 /* Pointer to the beginning of the input buffer. */
180 unsigned char *inbuf,
182 /* Number of characters read in each read call. */
183 int insize,
185 /* Pointer to the beginning of the output buffer. */
186 unsigned char *outbuf,
188 /* Number of characters written by each write call. */
189 int outsize,
191 /* Variables that have values according to the specified options. */
192 int quote,
193 int output_tabs,
194 int numbers,
195 int numbers_at_empty_lines,
196 int mark_line_ends,
197 int squeeze_empty_lines)
199 /* Last character read from the input buffer. */
200 unsigned char ch;
202 /* Pointer to the next character in the input buffer. */
203 unsigned char *bpin;
205 /* Pointer to the first non-valid byte in the input buffer, i.e. the
206 current end of the buffer. */
207 unsigned char *eob;
209 /* Pointer to the position where the next character shall be written. */
210 unsigned char *bpout;
212 /* Number of characters read by the last read call. */
213 int n_read;
215 /* Determines how many consecutive newlines there have been in the
216 input. 0 newlines makes NEWLINES -1, 1 newline makes NEWLINES 1,
217 etc. Initially 0 to indicate that we are at the beginning of a
218 new line. The "state" of the procedure is determined by
219 NEWLINES. */
220 int newlines = newlines2;
222 #ifdef FIONREAD
223 /* If nonzero, use the FIONREAD ioctl, as an optimization.
224 (On Ultrix, it is not supported on NFS filesystems.) */
225 int use_fionread = 1;
226 #endif
228 /* The inbuf pointers are initialized so that BPIN > EOB, and thereby input
229 is read immediately. */
231 eob = inbuf;
232 bpin = eob + 1;
234 bpout = outbuf;
236 for (;;)
240 /* Write if there are at least OUTSIZE bytes in OUTBUF. */
242 if (bpout - outbuf >= outsize)
244 unsigned char *wp = outbuf;
247 if (full_write (output_desc, wp, outsize) < 0)
248 error (1, errno, _("write error"));
249 wp += outsize;
251 while (bpout - wp >= outsize);
253 /* Move the remaining bytes to the beginning of the
254 buffer. */
256 memmove (outbuf, wp, bpout - wp);
257 bpout = outbuf + (bpout - wp);
260 /* Is INBUF empty? */
262 if (bpin > eob)
264 #ifdef FIONREAD
265 int n_to_read = 0;
267 /* Is there any input to read immediately?
268 If not, we are about to wait,
269 so write all buffered output before waiting. */
271 if (use_fionread
272 && ioctl (input_desc, FIONREAD, &n_to_read) < 0)
274 /* Ultrix returns EOPNOTSUPP on NFS;
275 HP-UX returns ENOTTY on pipes.
276 SunOS returns EINVAL and
277 More/BSD returns ENODEV on special files
278 like /dev/null.
279 Irix-5 returns ENOSYS on pipes. */
280 if (errno == EOPNOTSUPP || errno == ENOTTY
281 || errno == EINVAL || errno == ENODEV
282 #ifdef ENOSYS
283 || errno == ENOSYS
284 #endif
286 use_fionread = 0;
287 else
289 error (0, errno, _("cannot do ioctl on `%s'"), infile);
290 exit_stat = 1;
291 newlines2 = newlines;
292 return;
295 if (n_to_read == 0)
296 #endif
298 int n_write = bpout - outbuf;
300 if (full_write (output_desc, outbuf, n_write) < 0)
301 error (1, errno, _("write error"));
302 bpout = outbuf;
305 /* Read more input into INBUF. */
307 n_read = safe_read (input_desc, inbuf, insize);
308 if (n_read < 0)
310 error (0, errno, "%s", infile);
311 exit_stat = 1;
312 newlines2 = newlines;
313 return;
315 if (n_read == 0)
317 newlines2 = newlines;
318 return;
321 /* Update the pointers and insert a sentinel at the buffer
322 end. */
324 bpin = inbuf;
325 eob = bpin + n_read;
326 *eob = '\n';
328 else
330 /* It was a real (not a sentinel) newline. */
332 /* Was the last line empty?
333 (i.e. have two or more consecutive newlines been read?) */
335 if (++newlines > 0)
337 /* Are multiple adjacent empty lines to be substituted by
338 single ditto (-s), and this was the second empty line? */
340 if (squeeze_empty_lines && newlines >= 2)
342 ch = *bpin++;
343 continue;
346 /* Are line numbers to be written at empty lines (-n)? */
348 if (numbers && numbers_at_empty_lines)
350 next_line_num ();
351 bpout = (unsigned char *) stpcpy (bpout, line_num_print);
355 /* Output a currency symbol if requested (-e). */
357 if (mark_line_ends)
358 *bpout++ = '$';
360 /* Output the newline. */
362 *bpout++ = '\n';
364 ch = *bpin++;
366 while (ch == '\n');
368 /* Are we at the beginning of a line, and line numbers are requested? */
370 if (newlines >= 0 && numbers)
372 next_line_num ();
373 bpout = (unsigned char *) stpcpy (bpout, line_num_print);
376 /* Here CH cannot contain a newline character. */
378 /* The loops below continue until a newline character is found,
379 which means that the buffer is empty or that a proper newline
380 has been found. */
382 /* If quoting, i.e. at least one of -v, -e, or -t specified,
383 scan for chars that need conversion. */
384 if (quote)
385 for (;;)
387 if (ch >= 32)
389 if (ch < 127)
390 *bpout++ = ch;
391 else if (ch == 127)
392 *bpout++ = '^',
393 *bpout++ = '?';
394 else
396 *bpout++ = 'M',
397 *bpout++ = '-';
398 if (ch >= 128 + 32)
399 if (ch < 128 + 127)
400 *bpout++ = ch - 128;
401 else
402 *bpout++ = '^',
403 *bpout++ = '?';
404 else
405 *bpout++ = '^',
406 *bpout++ = ch - 128 + 64;
409 else if (ch == '\t' && output_tabs)
410 *bpout++ = '\t';
411 else if (ch == '\n')
413 newlines = -1;
414 break;
416 else
417 *bpout++ = '^',
418 *bpout++ = ch + 64;
420 ch = *bpin++;
422 else
423 /* Not quoting, neither of -v, -e, or -t specified. */
424 for (;;)
426 if (ch == '\t' && !output_tabs)
427 *bpout++ = '^',
428 *bpout++ = ch + 64;
429 else if (ch != '\n')
430 *bpout++ = ch;
431 else
433 newlines = -1;
434 break;
437 ch = *bpin++;
442 void
443 main (int argc, char **argv)
445 /* Optimal size of i/o operations of output. */
446 int outsize;
448 /* Optimal size of i/o operations of input. */
449 int insize;
451 /* Pointer to the input buffer. */
452 unsigned char *inbuf;
454 /* Pointer to the output buffer. */
455 unsigned char *outbuf;
457 int c;
459 /* Index in argv to processed argument. */
460 int argind;
462 /* Device number of the output (file or whatever). */
463 int out_dev;
465 /* I-node number of the output. */
466 int out_ino;
468 /* Nonzero if the output file should not be the same as any input file. */
469 int check_redirection = 1;
471 /* Nonzero if we have ever read standard input. */
472 int have_read_stdin = 0;
474 struct stat stat_buf;
476 /* Variables that are set according to the specified options. */
477 int numbers = 0;
478 int numbers_at_empty_lines = 1;
479 int squeeze_empty_lines = 0;
480 int mark_line_ends = 0;
481 int quote = 0;
482 int output_tabs = 1;
484 /* If nonzero, call cat, otherwise call simple_cat to do the actual work. */
485 int options = 0;
487 /* If nonzero, display usage information and exit. */
488 static int show_help;
490 /* If nonzero, print the version on standard output then exit. */
491 static int show_version;
493 static struct option const long_options[] =
495 {"number-nonblank", no_argument, NULL, 'b'},
496 {"number", no_argument, NULL, 'n'},
497 {"squeeze-blank", no_argument, NULL, 's'},
498 {"show-nonprinting", no_argument, NULL, 'v'},
499 {"show-ends", no_argument, NULL, 'E'},
500 {"show-tabs", no_argument, NULL, 'T'},
501 {"show-all", no_argument, NULL, 'A'},
502 {"help", no_argument, &show_help, 1},
503 {"version", no_argument, &show_version, 1},
504 {NULL, 0, NULL, 0}
507 program_name = argv[0];
509 /* Parse command line options. */
511 while ((c = getopt_long (argc, argv, "benstuvAET", long_options, (int *) 0))
512 != EOF)
514 switch (c)
516 case 0:
517 break;
519 case 'b':
520 ++options;
521 numbers = 1;
522 numbers_at_empty_lines = 0;
523 break;
525 case 'e':
526 ++options;
527 mark_line_ends = 1;
528 quote = 1;
529 break;
531 case 'n':
532 ++options;
533 numbers = 1;
534 break;
536 case 's':
537 ++options;
538 squeeze_empty_lines = 1;
539 break;
541 case 't':
542 ++options;
543 output_tabs = 0;
544 quote = 1;
545 break;
547 case 'u':
548 /* We provide the -u feature unconditionally. */
549 break;
551 case 'v':
552 ++options;
553 quote = 1;
554 break;
556 case 'A':
557 ++options;
558 quote = 1;
559 mark_line_ends = 1;
560 output_tabs = 0;
561 break;
563 case 'E':
564 ++options;
565 mark_line_ends = 1;
566 break;
568 case 'T':
569 ++options;
570 output_tabs = 0;
571 break;
573 default:
574 usage (2);
578 if (show_version)
580 printf ("cat - %s\n", version_string);
581 exit (0);
584 if (show_help)
585 usage (0);
587 output_desc = 1;
589 /* Get device, i-node number, and optimal blocksize of output. */
591 if (fstat (output_desc, &stat_buf) < 0)
592 error (1, errno, _("standard output"));
594 outsize = ST_BLKSIZE (stat_buf);
595 /* Input file can be output file for non-regular files.
596 fstat on pipes returns S_IFSOCK on some systems, S_IFIFO
597 on others, so the checking should not be done for those types,
598 and to allow things like cat < /dev/tty > /dev/tty, checking
599 is not done for device files either. */
601 if (S_ISREG (stat_buf.st_mode))
603 out_dev = stat_buf.st_dev;
604 out_ino = stat_buf.st_ino;
606 else
608 check_redirection = 0;
609 #ifdef lint /* Suppress `used before initialized' warning. */
610 out_dev = 0;
611 out_ino = 0;
612 #endif
615 /* Check if any of the input files are the same as the output file. */
617 /* Main loop. */
619 infile = "-";
620 argind = optind;
624 if (argind < argc)
625 infile = argv[argind];
627 if (infile[0] == '-' && infile[1] == 0)
629 have_read_stdin = 1;
630 input_desc = 0;
632 else
634 input_desc = open (infile, O_RDONLY);
635 if (input_desc < 0)
637 error (0, errno, "%s", infile);
638 exit_stat = 1;
639 continue;
643 if (fstat (input_desc, &stat_buf) < 0)
645 error (0, errno, "%s", infile);
646 exit_stat = 1;
647 goto contin;
649 insize = ST_BLKSIZE (stat_buf);
651 /* Compare the device and i-node numbers of this input file with
652 the corresponding values of the (output file associated with)
653 stdout, and skip this input file if they coincide. Input
654 files cannot be redirected to themselves. */
656 if (check_redirection
657 && stat_buf.st_dev == out_dev && stat_buf.st_ino == out_ino
658 && (input_desc != fileno (stdin) || output_desc != fileno (stdout)))
660 error (0, 0, _("%s: input file is output file"), infile);
661 exit_stat = 1;
662 goto contin;
665 /* Select which version of `cat' to use. If any options (more than -u,
666 --version, or --help) were specified, use `cat', otherwise use
667 `simple_cat'. */
669 if (options == 0)
671 insize = max (insize, outsize);
672 inbuf = (unsigned char *) xmalloc (insize);
674 simple_cat (inbuf, insize);
676 else
678 inbuf = (unsigned char *) xmalloc (insize + 1);
680 /* Why are (OUTSIZE - 1 + INSIZE * 4 + 13) bytes allocated for
681 the output buffer?
683 A test whether output needs to be written is done when the input
684 buffer empties or when a newline appears in the input. After
685 output is written, at most (OUTSIZE - 1) bytes will remain in the
686 buffer. Now INSIZE bytes of input is read. Each input character
687 may grow by a factor of 4 (by the prepending of M-^). If all
688 characters do, and no newlines appear in this block of input, we
689 will have at most (OUTSIZE - 1 + INSIZE) bytes in the buffer. If
690 the last character in the preceding block of input was a
691 newline, a line number may be written (according to the given
692 options) as the first thing in the output buffer. (Done after the
693 new input is read, but before processing of the input begins.) A
694 line number requires seldom more than 13 positions. */
696 outbuf = (unsigned char *) xmalloc (outsize - 1 + insize * 4 + 13);
698 cat (inbuf, insize, outbuf, outsize, quote,
699 output_tabs, numbers, numbers_at_empty_lines, mark_line_ends,
700 squeeze_empty_lines);
702 free (outbuf);
705 free (inbuf);
707 contin:
708 if (strcmp (infile, "-") && close (input_desc) < 0)
710 error (0, errno, "%s", infile);
711 exit_stat = 1;
714 while (++argind < argc);
716 if (have_read_stdin && close (0) < 0)
717 error (1, errno, "-");
718 if (close (1) < 0)
719 error (1, errno, _("write error"));
721 exit (exit_stat);