TODO: add an item for a chmod optimization
[platform/upstream/coreutils.git] / src / tee.c
1 /* tee - read from standard input and write to standard output and files.
2    Copyright (C) 85,1990-2006, 2008 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 3 of the License, or
7    (at your option) 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, see <http://www.gnu.org/licenses/>.  */
16
17 /* Mike Parker, Richard M. Stallman, and David MacKenzie */
18
19 #include <config.h>
20 #include <sys/types.h>
21 #include <signal.h>
22 #include <getopt.h>
23
24 #include "system.h"
25 #include "error.h"
26 #include "stdio--.h"
27
28 /* The official name of this program (e.g., no `g' prefix).  */
29 #define PROGRAM_NAME "tee"
30
31 #define AUTHORS \
32   proper_name ("Mike Parker"), \
33   proper_name ("Richard M. Stallman"), \
34   proper_name ("David MacKenzie")
35
36 static bool tee_files (int nfiles, const char **files);
37
38 /* If true, append to output files rather than truncating them. */
39 static bool append;
40
41 /* If true, ignore interrupts. */
42 static bool ignore_interrupts;
43
44 static struct option const long_options[] =
45 {
46   {"append", no_argument, NULL, 'a'},
47   {"ignore-interrupts", no_argument, NULL, 'i'},
48   {GETOPT_HELP_OPTION_DECL},
49   {GETOPT_VERSION_OPTION_DECL},
50   {NULL, 0, NULL, 0}
51 };
52
53 void
54 usage (int status)
55 {
56   if (status != EXIT_SUCCESS)
57     fprintf (stderr, _("Try `%s --help' for more information.\n"),
58              program_name);
59   else
60     {
61       printf (_("Usage: %s [OPTION]... [FILE]...\n"), program_name);
62       fputs (_("\
63 Copy standard input to each FILE, and also to standard output.\n\
64 \n\
65   -a, --append              append to the given FILEs, do not overwrite\n\
66   -i, --ignore-interrupts   ignore interrupt signals\n\
67 "), stdout);
68       fputs (HELP_OPTION_DESCRIPTION, stdout);
69       fputs (VERSION_OPTION_DESCRIPTION, stdout);
70       fputs (_("\
71 \n\
72 If a FILE is -, copy again to standard output.\n\
73 "), stdout);
74       emit_bug_reporting_address ();
75     }
76   exit (status);
77 }
78
79 int
80 main (int argc, char **argv)
81 {
82   bool ok;
83   int optc;
84
85   initialize_main (&argc, &argv);
86   set_program_name (argv[0]);
87   setlocale (LC_ALL, "");
88   bindtextdomain (PACKAGE, LOCALEDIR);
89   textdomain (PACKAGE);
90
91   atexit (close_stdout);
92
93   append = false;
94   ignore_interrupts = false;
95
96   while ((optc = getopt_long (argc, argv, "ai", long_options, NULL)) != -1)
97     {
98       switch (optc)
99         {
100         case 'a':
101           append = true;
102           break;
103
104         case 'i':
105           ignore_interrupts = true;
106           break;
107
108         case_GETOPT_HELP_CHAR;
109
110         case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
111
112         default:
113           usage (EXIT_FAILURE);
114         }
115     }
116
117   if (ignore_interrupts)
118     signal (SIGINT, SIG_IGN);
119
120   /* Do *not* warn if tee is given no file arguments.
121      POSIX requires that it work when given no arguments.  */
122
123   ok = tee_files (argc - optind, (const char **) &argv[optind]);
124   if (close (STDIN_FILENO) != 0)
125     error (EXIT_FAILURE, errno, _("standard input"));
126
127   exit (ok ? EXIT_SUCCESS : EXIT_FAILURE);
128 }
129
130 /* Copy the standard input into each of the NFILES files in FILES
131    and into the standard output.
132    Return true if successful.  */
133
134 static bool
135 tee_files (int nfiles, const char **files)
136 {
137   FILE **descriptors;
138   char buffer[BUFSIZ];
139   ssize_t bytes_read;
140   int i;
141   bool ok = true;
142   char const *mode_string =
143     (O_BINARY
144      ? (append ? "ab" : "wb")
145      : (append ? "a" : "w"));
146
147   descriptors = xnmalloc (nfiles + 1, sizeof *descriptors);
148
149   /* Move all the names `up' one in the argv array to make room for
150      the entry for standard output.  This writes into argv[argc].  */
151   for (i = nfiles; i >= 1; i--)
152     files[i] = files[i - 1];
153
154   if (O_BINARY && ! isatty (STDIN_FILENO))
155     freopen (NULL, "rb", stdin);
156   if (O_BINARY && ! isatty (STDOUT_FILENO))
157     freopen (NULL, "wb", stdout);
158
159   /* In the array of NFILES + 1 descriptors, make
160      the first one correspond to standard output.   */
161   descriptors[0] = stdout;
162   files[0] = _("standard output");
163   setvbuf (stdout, NULL, _IONBF, 0);
164
165   for (i = 1; i <= nfiles; i++)
166     {
167       descriptors[i] = (STREQ (files[i], "-")
168                         ? stdout
169                         : fopen (files[i], mode_string));
170       if (descriptors[i] == NULL)
171         {
172           error (0, errno, "%s", files[i]);
173           ok = false;
174         }
175       else
176         setvbuf (descriptors[i], NULL, _IONBF, 0);
177     }
178
179   while (1)
180     {
181       bytes_read = read (0, buffer, sizeof buffer);
182 #ifdef EINTR
183       if (bytes_read < 0 && errno == EINTR)
184         continue;
185 #endif
186       if (bytes_read <= 0)
187         break;
188
189       /* Write to all NFILES + 1 descriptors.
190          Standard output is the first one.  */
191       for (i = 0; i <= nfiles; i++)
192         if (descriptors[i]
193             && fwrite (buffer, bytes_read, 1, descriptors[i]) != 1)
194           {
195             error (0, errno, "%s", files[i]);
196             descriptors[i] = NULL;
197             ok = false;
198           }
199     }
200
201   if (bytes_read == -1)
202     {
203       error (0, errno, _("read error"));
204       ok = false;
205     }
206
207   /* Close the files, but not standard output.  */
208   for (i = 1; i <= nfiles; i++)
209     if (!STREQ (files[i], "-")
210         && descriptors[i] && fclose (descriptors[i]) != 0)
211       {
212         error (0, errno, "%s", files[i]);
213         ok = false;
214       }
215
216   free (descriptors);
217
218   return ok;
219 }