Use STREQ rather than strcmp
[platform/upstream/coreutils.git] / src / cat.c
1 /* cat -- concatenate files and print on the standard output.
2    Copyright (C) 88, 90, 91, 95, 96, 1997, 1998 Free Software Foundation, Inc.
3
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.
8
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.
13
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.  */
17
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.
22
23    By tege@sics.se, Torbjorn Granlund, advised by rms, Richard Stallman. */
24
25 #include <config.h>
26
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"
36
37 /* Undefine, to avoid warning about redefinition on some systems.  */
38 #undef max
39 #define max(h,i) ((h) > (i) ? (h) : (i))
40
41 int full_write ();
42
43 /* Name under which this program was invoked.  */
44 char *program_name;
45
46 /* Name of input file.  May be "-".  */
47 static char *infile;
48
49 /* Descriptor on which input file is open.  */
50 static int input_desc;
51
52 /* Descriptor on which output file is open.  Always is 1.  */
53 static int output_desc;
54
55 /* Buffer for line numbers.  */
56 static char line_buf[13] =
57 {' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '0', '\t', '\0'};
58
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;
62
63 /* Position of the first digit in `line_buf'.  */
64 static char *line_num_start = line_buf + 10;
65
66 /* Position of the last digit in `line_buf'.  */
67 static char *line_num_end = line_buf + 10;
68
69 /* Preserves the `cat' function's local `newlines' between invocations.  */
70 static int newlines2 = 0;
71
72 /* Count of non-fatal error conditions.  */
73 static int exit_status = 0;
74
75 static void
76 usage (int status)
77 {
78   if (status != 0)
79     fprintf (stderr, _("Try `%s --help' for more information.\n"),
80              program_name);
81   else
82     {
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\
102 \n\
103 With no FILE, or when FILE is -, read standard input.\n\
104 "));
105       puts (_("\nReport bugs to <textutils-bugs@gnu.org>."));
106     }
107   exit (status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
108 }
109
110 /* Compute the next line number.  */
111
112 static void
113 next_line_num (void)
114 {
115   char *endp = line_num_end;
116   do
117     {
118       if ((*endp)++ < '9')
119         return;
120       *endp-- = '0';
121     }
122   while (endp >= line_num_start);
123   *--line_num_start = '1';
124   if (line_num_start < line_num_print)
125     line_num_print--;
126 }
127
128 /* Plain cat.  Copies the file behind `input_desc' to the file behind
129    `output_desc'.  */
130
131 static void
132 simple_cat (
133      /* Pointer to the buffer, used by reads and writes.  */
134      unsigned char *buf,
135
136      /* Number of characters preferably read or written by each read and write
137         call.  */
138      int bufsize)
139 {
140   /* Actual number of characters read, and therefore written.  */
141   int n_read;
142
143   /* Loop until the end of the file.  */
144
145   for (;;)
146     {
147       /* Read a block of input.  */
148
149       n_read = safe_read (input_desc, buf, bufsize);
150       if (n_read < 0)
151         {
152           error (0, errno, "%s", infile);
153           exit_status = 1;
154           return;
155         }
156
157       /* End of this file?  */
158
159       if (n_read == 0)
160         break;
161
162       /* Write this block out.  */
163
164       if (full_write (output_desc, buf, n_read) < 0)
165         error (EXIT_FAILURE, errno, _("write error"));
166     }
167 }
168
169 /* Cat the file behind INPUT_DESC to the file behind OUTPUT_DESC.
170    Called if any option more than -u was specified.
171
172    A newline character is always put at the end of the buffer, to make
173    an explicit test for buffer end unnecessary.  */
174
175 static void
176 cat (
177      /* Pointer to the beginning of the input buffer.  */
178      unsigned char *inbuf,
179
180      /* Number of characters read in each read call.  */
181      int insize,
182
183      /* Pointer to the beginning of the output buffer.  */
184      unsigned char *outbuf,
185
186      /* Number of characters written by each write call.  */
187      int outsize,
188
189      /* Variables that have values according to the specified options.  */
190      int quote,
191      int output_tabs,
192      int numbers,
193      int numbers_at_empty_lines,
194      int mark_line_ends,
195      int squeeze_empty_lines)
196 {
197   /* Last character read from the input buffer.  */
198   unsigned char ch;
199
200   /* Pointer to the next character in the input buffer.  */
201   unsigned char *bpin;
202
203   /* Pointer to the first non-valid byte in the input buffer, i.e. the
204      current end of the buffer.  */
205   unsigned char *eob;
206
207   /* Pointer to the position where the next character shall be written.  */
208   unsigned char *bpout;
209
210   /* Number of characters read by the last read call.  */
211   int n_read;
212
213   /* Determines how many consecutive newlines there have been in the
214      input.  0 newlines makes NEWLINES -1, 1 newline makes NEWLINES 1,
215      etc.  Initially 0 to indicate that we are at the beginning of a
216      new line.  The "state" of the procedure is determined by
217      NEWLINES.  */
218   int newlines = newlines2;
219
220 #ifdef FIONREAD
221   /* If nonzero, use the FIONREAD ioctl, as an optimization.
222      (On Ultrix, it is not supported on NFS filesystems.)  */
223   int use_fionread = 1;
224 #endif
225
226   /* The inbuf pointers are initialized so that BPIN > EOB, and thereby input
227      is read immediately.  */
228
229   eob = inbuf;
230   bpin = eob + 1;
231
232   bpout = outbuf;
233
234   for (;;)
235     {
236       do
237         {
238           /* Write if there are at least OUTSIZE bytes in OUTBUF.  */
239
240           if (bpout - outbuf >= outsize)
241             {
242               unsigned char *wp = outbuf;
243               do
244                 {
245                   if (full_write (output_desc, wp, outsize) < 0)
246                     error (EXIT_FAILURE, errno, _("write error"));
247                   wp += outsize;
248                 }
249               while (bpout - wp >= outsize);
250
251               /* Move the remaining bytes to the beginning of the
252                  buffer.  */
253
254               memmove (outbuf, wp, bpout - wp);
255               bpout = outbuf + (bpout - wp);
256             }
257
258           /* Is INBUF empty?  */
259
260           if (bpin > eob)
261             {
262 #ifdef FIONREAD
263               int n_to_read = 0;
264
265               /* Is there any input to read immediately?
266                  If not, we are about to wait,
267                  so write all buffered output before waiting.  */
268
269               if (use_fionread
270                   && ioctl (input_desc, FIONREAD, &n_to_read) < 0)
271                 {
272                   /* Ultrix returns EOPNOTSUPP on NFS;
273                      HP-UX returns ENOTTY on pipes.
274                      SunOS returns EINVAL and
275                      More/BSD returns ENODEV on special files
276                      like /dev/null.
277                      Irix-5 returns ENOSYS on pipes.  */
278                   if (errno == EOPNOTSUPP || errno == ENOTTY
279                       || errno == EINVAL || errno == ENODEV
280 # ifdef ENOSYS
281                       || errno == ENOSYS
282 # endif
283                       )
284                     use_fionread = 0;
285                   else
286                     {
287                       error (0, errno, _("cannot do ioctl on `%s'"), infile);
288                       exit_status = 1;
289                       newlines2 = newlines;
290                       return;
291                     }
292                 }
293               if (n_to_read == 0)
294 #endif
295                 {
296                   int n_write = bpout - outbuf;
297
298                   if (full_write (output_desc, outbuf, n_write) < 0)
299                     error (EXIT_FAILURE, errno, _("write error"));
300                   bpout = outbuf;
301                 }
302
303               /* Read more input into INBUF.  */
304
305               n_read = safe_read (input_desc, inbuf, insize);
306               if (n_read < 0)
307                 {
308                   error (0, errno, "%s", infile);
309                   exit_status = 1;
310                   newlines2 = newlines;
311                   return;
312                 }
313               if (n_read == 0)
314                 {
315                   newlines2 = newlines;
316                   return;
317                 }
318
319               /* Update the pointers and insert a sentinel at the buffer
320                  end.  */
321
322               bpin = inbuf;
323               eob = bpin + n_read;
324               *eob = '\n';
325             }
326           else
327             {
328               /* It was a real (not a sentinel) newline.  */
329
330               /* Was the last line empty?
331                  (i.e. have two or more consecutive newlines been read?)  */
332
333               if (++newlines > 0)
334                 {
335                   /* Are multiple adjacent empty lines to be substituted by
336                      single ditto (-s), and this was the second empty line?  */
337
338                   if (squeeze_empty_lines && newlines >= 2)
339                     {
340                       ch = *bpin++;
341                       continue;
342                     }
343
344                   /* Are line numbers to be written at empty lines (-n)?  */
345
346                   if (numbers && numbers_at_empty_lines)
347                     {
348                       next_line_num ();
349                       bpout = (unsigned char *) stpcpy ((char *) bpout,
350                                                         line_num_print);
351                     }
352                 }
353
354               /* Output a currency symbol if requested (-e).  */
355
356               if (mark_line_ends)
357                 *bpout++ = '$';
358
359               /* Output the newline.  */
360
361               *bpout++ = '\n';
362             }
363           ch = *bpin++;
364         }
365       while (ch == '\n');
366
367       /* Are we at the beginning of a line, and line numbers are requested?  */
368
369       if (newlines >= 0 && numbers)
370         {
371           next_line_num ();
372           bpout = (unsigned char *) stpcpy ((char *) bpout, line_num_print);
373         }
374
375       /* Here CH cannot contain a newline character.  */
376
377       /* The loops below continue until a newline character is found,
378          which means that the buffer is empty or that a proper newline
379          has been found.  */
380
381       /* If quoting, i.e. at least one of -v, -e, or -t specified,
382          scan for chars that need conversion.  */
383       if (quote)
384         {
385           for (;;)
386             {
387               if (ch >= 32)
388                 {
389                   if (ch < 127)
390                     *bpout++ = ch;
391                   else if (ch == 127)
392                     {
393                       *bpout++ = '^';
394                       *bpout++ = '?';
395                     }
396                   else
397                     {
398                       *bpout++ = 'M';
399                       *bpout++ = '-';
400                       if (ch >= 128 + 32)
401                         {
402                           if (ch < 128 + 127)
403                             *bpout++ = ch - 128;
404                           else
405                             {
406                               *bpout++ = '^';
407                               *bpout++ = '?';
408                             }
409                         }
410                       else
411                         {
412                           *bpout++ = '^';
413                           *bpout++ = ch - 128 + 64;
414                         }
415                     }
416                 }
417               else if (ch == '\t' && output_tabs)
418                 *bpout++ = '\t';
419               else if (ch == '\n')
420                 {
421                   newlines = -1;
422                   break;
423                 }
424               else
425                 {
426                   *bpout++ = '^';
427                   *bpout++ = ch + 64;
428                 }
429
430               ch = *bpin++;
431             }
432         }
433       else
434         {
435           /* Not quoting, neither of -v, -e, or -t specified.  */
436           for (;;)
437             {
438               if (ch == '\t' && !output_tabs)
439                 {
440                   *bpout++ = '^';
441                   *bpout++ = ch + 64;
442                 }
443               else if (ch != '\n')
444                 *bpout++ = ch;
445               else
446                 {
447                   newlines = -1;
448                   break;
449                 }
450
451               ch = *bpin++;
452             }
453         }
454     }
455 }
456
457 int
458 main (int argc, char **argv)
459 {
460   /* Optimal size of i/o operations of output.  */
461   int outsize;
462
463   /* Optimal size of i/o operations of input.  */
464   int insize;
465
466   /* Pointer to the input buffer.  */
467   unsigned char *inbuf;
468
469   /* Pointer to the output buffer.  */
470   unsigned char *outbuf;
471
472   int c;
473
474   /* Index in argv to processed argument.  */
475   int argind;
476
477   /* Device number of the output (file or whatever).  */
478   int out_dev;
479
480   /* I-node number of the output.  */
481   int out_ino;
482
483   /* Nonzero if the output file should not be the same as any input file. */
484   int check_redirection = 1;
485
486   /* Nonzero if we have ever read standard input. */
487   int have_read_stdin = 0;
488
489   struct stat stat_buf;
490
491   /* Variables that are set according to the specified options.  */
492   int numbers = 0;
493   int numbers_at_empty_lines = 1;
494   int squeeze_empty_lines = 0;
495   int mark_line_ends = 0;
496   int quote = 0;
497   int output_tabs = 1;
498
499 /* If nonzero, call cat, otherwise call simple_cat to do the actual work. */
500   int options = 0;
501
502   /* If nonzero, display usage information and exit.  */
503   static int show_help;
504
505   /* If nonzero, print the version on standard output then exit.  */
506   static int show_version;
507
508   static struct option const long_options[] =
509   {
510     {"number-nonblank", no_argument, NULL, 'b'},
511     {"number", no_argument, NULL, 'n'},
512     {"squeeze-blank", no_argument, NULL, 's'},
513     {"show-nonprinting", no_argument, NULL, 'v'},
514     {"show-ends", no_argument, NULL, 'E'},
515     {"show-tabs", no_argument, NULL, 'T'},
516     {"show-all", no_argument, NULL, 'A'},
517     {"help", no_argument, &show_help, 1},
518     {"version", no_argument, &show_version, 1},
519     {NULL, 0, NULL, 0}
520   };
521
522   program_name = argv[0];
523   setlocale (LC_ALL, "");
524   bindtextdomain (PACKAGE, LOCALEDIR);
525   textdomain (PACKAGE);
526
527   /* Parse command line options.  */
528
529   while ((c = getopt_long (argc, argv, "benstuvAET", long_options, NULL)) != -1)
530     {
531       switch (c)
532         {
533         case 0:
534           break;
535
536         case 'b':
537           ++options;
538           numbers = 1;
539           numbers_at_empty_lines = 0;
540           break;
541
542         case 'e':
543           ++options;
544           mark_line_ends = 1;
545           quote = 1;
546           break;
547
548         case 'n':
549           ++options;
550           numbers = 1;
551           break;
552
553         case 's':
554           ++options;
555           squeeze_empty_lines = 1;
556           break;
557
558         case 't':
559           ++options;
560           output_tabs = 0;
561           quote = 1;
562           break;
563
564         case 'u':
565           /* We provide the -u feature unconditionally.  */
566           break;
567
568         case 'v':
569           ++options;
570           quote = 1;
571           break;
572
573         case 'A':
574           ++options;
575           quote = 1;
576           mark_line_ends = 1;
577           output_tabs = 0;
578           break;
579
580         case 'E':
581           ++options;
582           mark_line_ends = 1;
583           break;
584
585         case 'T':
586           ++options;
587           output_tabs = 0;
588           break;
589
590         default:
591           usage (EXIT_FAILURE);
592         }
593     }
594
595   if (show_version)
596     {
597       printf ("cat (%s) %s\n", GNU_PACKAGE, VERSION);
598       exit (EXIT_SUCCESS);
599     }
600
601   if (show_help)
602     usage (0);
603
604   output_desc = 1;
605
606   /* Get device, i-node number, and optimal blocksize of output.  */
607
608   if (fstat (output_desc, &stat_buf) < 0)
609     error (EXIT_FAILURE, errno, _("standard output"));
610
611   outsize = ST_BLKSIZE (stat_buf);
612   /* Input file can be output file for non-regular files.
613      fstat on pipes returns S_IFSOCK on some systems, S_IFIFO
614      on others, so the checking should not be done for those types,
615      and to allow things like cat < /dev/tty > /dev/tty, checking
616      is not done for device files either. */
617
618   if (S_ISREG (stat_buf.st_mode))
619     {
620       out_dev = stat_buf.st_dev;
621       out_ino = stat_buf.st_ino;
622     }
623   else
624     {
625       check_redirection = 0;
626 #ifdef lint  /* Suppress `used before initialized' warning.  */
627       out_dev = 0;
628       out_ino = 0;
629 #endif
630     }
631
632   /* Check if any of the input files are the same as the output file.  */
633
634   /* Main loop.  */
635
636   infile = "-";
637   argind = optind;
638
639   do
640     {
641       if (argind < argc)
642         infile = argv[argind];
643
644       if (infile[0] == '-' && infile[1] == 0)
645         {
646           have_read_stdin = 1;
647           input_desc = 0;
648         }
649       else
650         {
651           input_desc = open (infile, O_RDONLY);
652           if (input_desc < 0)
653             {
654               error (0, errno, "%s", infile);
655               exit_status = 1;
656               continue;
657             }
658         }
659
660       if (fstat (input_desc, &stat_buf) < 0)
661         {
662           error (0, errno, "%s", infile);
663           exit_status = 1;
664           goto contin;
665         }
666       insize = ST_BLKSIZE (stat_buf);
667
668       /* Compare the device and i-node numbers of this input file with
669          the corresponding values of the (output file associated with)
670          stdout, and skip this input file if they coincide.  Input
671          files cannot be redirected to themselves.  */
672
673       if (check_redirection
674           && stat_buf.st_dev == out_dev && stat_buf.st_ino == out_ino
675           && (input_desc != STDIN_FILENO || output_desc != STDOUT_FILENO))
676         {
677           error (0, 0, _("%s: input file is output file"), infile);
678           exit_status = 1;
679           goto contin;
680         }
681
682       /* Select which version of `cat' to use. If any options (more than -u,
683          --version, or --help) were specified, use `cat', otherwise use
684          `simple_cat'.  */
685
686       if (options == 0)
687         {
688           insize = max (insize, outsize);
689           inbuf = (unsigned char *) xmalloc (insize);
690
691           simple_cat (inbuf, insize);
692         }
693       else
694         {
695           inbuf = (unsigned char *) xmalloc (insize + 1);
696
697           /* Why are (OUTSIZE  - 1 + INSIZE * 4 + 13) bytes allocated for
698              the output buffer?
699
700              A test whether output needs to be written is done when the input
701              buffer empties or when a newline appears in the input.  After
702              output is written, at most (OUTSIZE - 1) bytes will remain in the
703              buffer.  Now INSIZE bytes of input is read.  Each input character
704              may grow by a factor of 4 (by the prepending of M-^).  If all
705              characters do, and no newlines appear in this block of input, we
706              will have at most (OUTSIZE - 1 + INSIZE) bytes in the buffer.  If
707              the last character in the preceding block of input was a
708              newline, a line number may be written (according to the given
709              options) as the first thing in the output buffer. (Done after the
710              new input is read, but before processing of the input begins.)  A
711              line number requires seldom more than 13 positions.  */
712
713           outbuf = (unsigned char *) xmalloc (outsize - 1 + insize * 4 + 13);
714
715           cat (inbuf, insize, outbuf, outsize, quote,
716                output_tabs, numbers, numbers_at_empty_lines, mark_line_ends,
717                squeeze_empty_lines);
718
719           free (outbuf);
720         }
721
722       free (inbuf);
723
724     contin:
725       if (!STREQ (infile, "-") && close (input_desc) < 0)
726         {
727           error (0, errno, "%s", infile);
728           exit_status = 1;
729         }
730     }
731   while (++argind < argc);
732
733   if (have_read_stdin && close (0) < 0)
734     error (EXIT_FAILURE, errno, "-");
735   if (close (1) < 0)
736     error (EXIT_FAILURE, errno, _("write error"));
737
738   exit (exit_status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
739 }