Include safe-read.h instead of merely declaring safe_read.
[platform/upstream/coreutils.git] / src / head.c
1 /* head -- output first part of file(s)
2    Copyright (C) 89, 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 /* Options: (see usage)
19    Reads from standard input if no files are given or when a filename of
20    ``-'' is encountered.
21    By default, filename headers are printed only if more than one file
22    is given.
23    By default, prints the first 10 lines (head -n 10).
24
25    David MacKenzie <djm@gnu.ai.mit.edu> */
26
27 #include <config.h>
28
29 #include <stdio.h>
30 #include <getopt.h>
31 #include <sys/types.h>
32 #include "system.h"
33 #include "error.h"
34 #include "xstrtoul.h"
35 #include "safe-read.h"
36
37 /* FIXME: someday, make this really *be* `long long'.  */
38 typedef long int U_LONG_LONG;
39
40 /* Number of lines/chars/blocks to head. */
41 #define DEFAULT_NUMBER 10
42
43 /* Size of atomic reads. */
44 #define BUFSIZE (512 * 8)
45
46 /* If nonzero, print filename headers. */
47 static int print_headers;
48
49 /* When to print the filename banners. */
50 enum header_mode
51 {
52   multiple_files, always, never
53 };
54
55 /* The name this program was run with. */
56 char *program_name;
57
58 /* Have we ever read standard input?  */
59 static int have_read_stdin;
60
61 /* If nonzero, display usage information and exit.  */
62 static int show_help;
63
64 /* If nonzero, print the version on standard output then exit.  */
65 static int show_version;
66
67 static struct option const long_options[] =
68 {
69   {"bytes", required_argument, NULL, 'c'},
70   {"lines", required_argument, NULL, 'n'},
71   {"quiet", no_argument, NULL, 'q'},
72   {"silent", no_argument, NULL, 'q'},
73   {"verbose", no_argument, NULL, 'v'},
74   {"help", no_argument, &show_help, 1},
75   {"version", no_argument, &show_version, 1},
76   {NULL, 0, NULL, 0}
77 };
78
79 static void
80 usage (int status)
81 {
82   if (status != 0)
83     fprintf (stderr, _("Try `%s --help' for more information.\n"),
84              program_name);
85   else
86     {
87       printf (_("\
88 Usage: %s [OPTION]... [FILE]...\n\
89 "),
90               program_name);
91       printf (_("\
92 Print first 10 lines of each FILE to standard output.\n\
93 With more than one FILE, precede each with a header giving the file name.\n\
94 With no FILE, or when FILE is -, read standard input.\n\
95 \n\
96   -c, --bytes=SIZE         print first SIZE bytes\n\
97   -n, --lines=NUMBER       print first NUMBER lines instead of first 10\n\
98   -q, --quiet, --silent    never print headers giving file names\n\
99   -v, --verbose            always print headers giving file names\n\
100       --help               display this help and exit\n\
101       --version            output version information and exit\n\
102 \n\
103 SIZE may have a multiplier suffix: b for 512, k for 1K, m for 1 Meg.\n\
104 If -VALUE is used as first OPTION, read -c VALUE when one of\n\
105 multipliers bkm follows concatenated, else read -n VALUE.\n\
106 "));
107       puts (_("\nReport bugs to <textutils-bugs@gnu.org>."));
108     }
109   exit (status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
110 }
111
112 static void
113 write_header (const char *filename)
114 {
115   static int first_file = 1;
116
117   printf ("%s==> %s <==\n", (first_file ? "" : "\n"), filename);
118   first_file = 0;
119 }
120
121 static int
122 head_bytes (const char *filename, int fd, U_LONG_LONG bytes_to_write)
123 {
124   char buffer[BUFSIZE];
125   int bytes_read;
126
127   while (bytes_to_write)
128     {
129       bytes_read = safe_read (fd, buffer, BUFSIZE);
130       if (bytes_read < 0)
131         {
132           error (0, errno, "%s", filename);
133           return 1;
134         }
135       if (bytes_read == 0)
136         break;
137       if (bytes_read > bytes_to_write)
138         bytes_read = bytes_to_write;
139       if (fwrite (buffer, 1, bytes_read, stdout) == 0)
140         error (EXIT_FAILURE, errno, _("write error"));
141       bytes_to_write -= bytes_read;
142     }
143   return 0;
144 }
145
146 static int
147 head_lines (const char *filename, int fd, U_LONG_LONG lines_to_write)
148 {
149   char buffer[BUFSIZE];
150   int bytes_read;
151   int bytes_to_write;
152
153   while (lines_to_write)
154     {
155       bytes_read = safe_read (fd, buffer, BUFSIZE);
156       if (bytes_read < 0)
157         {
158           error (0, errno, "%s", filename);
159           return 1;
160         }
161       if (bytes_read == 0)
162         break;
163       bytes_to_write = 0;
164       while (bytes_to_write < bytes_read)
165         if (buffer[bytes_to_write++] == '\n' && --lines_to_write == 0)
166           break;
167       if (fwrite (buffer, 1, bytes_to_write, stdout) == 0)
168         error (EXIT_FAILURE, errno, _("write error"));
169     }
170   return 0;
171 }
172
173 static int
174 head (const char *filename, int fd, U_LONG_LONG n_units, int count_lines)
175 {
176   if (count_lines)
177     return head_lines (filename, fd, n_units);
178   else
179     return head_bytes (filename, fd, n_units);
180 }
181
182 static int
183 head_file (const char *filename, U_LONG_LONG n_units, int count_lines)
184 {
185   int fd;
186
187   if (!strcmp (filename, "-"))
188     {
189       have_read_stdin = 1;
190       filename = _("standard input");
191       if (print_headers)
192         write_header (filename);
193       return head (filename, 0, n_units, count_lines);
194     }
195   else
196     {
197       fd = open (filename, O_RDONLY);
198       if (fd >= 0)
199         {
200           int errors;
201
202           if (print_headers)
203             write_header (filename);
204           errors = head (filename, fd, n_units, count_lines);
205           if (close (fd) == 0)
206             return errors;
207         }
208       error (0, errno, "%s", filename);
209       return 1;
210     }
211 }
212
213 /* Convert a string of digits, N_STRING, with a single, optional suffix
214    character (b, k, or m) to an integral value.  Upon successful conversion,
215    return that value.  If it cannot be converted, give a diagnostic and exit.
216    COUNT_LINES indicates whether N_STRING is a number of bytes or a number
217    of lines.  It is used solely to give a more specific diagnostic.  */
218
219 static U_LONG_LONG
220 string_to_ull (int count_lines, const char *n_string)
221 {
222   strtol_error s_err;
223   unsigned long int tmp_ulong;
224
225   s_err = xstrtoul (n_string, NULL, 0, &tmp_ulong, "bkm");
226
227   if (s_err == LONGINT_INVALID)
228     {
229       error (EXIT_FAILURE, 0, "%s: %s", n_string,
230              (count_lines
231               ? _("invalid number of lines")
232               : _("invalid number of bytes")));
233     }
234
235   if (s_err != LONGINT_OK)
236     {
237       error (EXIT_FAILURE, 0,
238              _("%s: %s is so large that it is not representable"), n_string,
239              count_lines ? _("number of lines") : _("number of bytes"));
240     }
241
242   return tmp_ulong;
243 }
244
245 int
246 main (int argc, char **argv)
247 {
248   enum header_mode header_mode = multiple_files;
249   int exit_status = 0;
250   char *n_string;
251   int c;
252
253   /* Number of items to print. */
254   U_LONG_LONG n_units = DEFAULT_NUMBER;
255
256   /* If nonzero, interpret the numeric argument as the number of lines.
257      Otherwise, interpret it as the number of bytes.  */
258   int count_lines = 1;
259
260   program_name = argv[0];
261   setlocale (LC_ALL, "");
262   bindtextdomain (PACKAGE, LOCALEDIR);
263   textdomain (PACKAGE);
264
265   have_read_stdin = 0;
266
267   print_headers = 0;
268
269   if (argc > 1 && argv[1][0] == '-' && ISDIGIT (argv[1][1]))
270     {
271       char *end_n_string;
272       char multiplier_char = 0;
273
274       n_string = &argv[1][1];
275
276       /* Old option syntax; a dash, one or more digits, and one or
277          more option letters.  Move past the number. */
278       for (++argv[1]; ISDIGIT (*argv[1]); ++argv[1])
279         {
280           /* empty */
281         }
282
283       /* Pointer to the byte after the last digit.  */
284       end_n_string = argv[1];
285
286       /* Parse any appended option letters. */
287       while (*argv[1])
288         {
289           switch (*argv[1])
290             {
291             case 'c':
292               count_lines = 0;
293               multiplier_char = 0;
294               break;
295
296             case 'b':
297             case 'k':
298             case 'm':
299               count_lines = 0;
300               multiplier_char = *argv[1];
301               break;
302
303             case 'l':
304               count_lines = 1;
305               break;
306
307             case 'q':
308               header_mode = never;
309               break;
310
311             case 'v':
312               header_mode = always;
313               break;
314
315             default:
316               error (0, 0, _("unrecognized option `-%c'"), *argv[1]);
317               usage (1);
318             }
319           ++argv[1];
320         }
321
322       /* Append the multiplier character (if any) onto the end of
323          the digit string.  Then add NUL byte if necessary.  */
324       *end_n_string = multiplier_char;
325       if (multiplier_char)
326         *(++end_n_string) = 0;
327
328       n_units = string_to_ull (count_lines, n_string);
329
330       /* Make the options we just parsed invisible to getopt. */
331       argv[1] = argv[0];
332       argv++;
333       argc--;
334
335       /* FIXME: allow POSIX options if there were obsolescent ones?  */
336
337     }
338
339
340   while ((c = getopt_long (argc, argv, "c:n:qv", long_options, NULL)) != -1)
341     {
342       switch (c)
343         {
344         case 0:
345           break;
346
347         case 'c':
348           count_lines = 0;
349           n_units = string_to_ull (count_lines, optarg);
350           break;
351
352         case 'n':
353           count_lines = 1;
354           n_units = string_to_ull (count_lines, optarg);
355           break;
356
357         case 'q':
358           header_mode = never;
359           break;
360
361         case 'v':
362           header_mode = always;
363           break;
364
365         default:
366           usage (1);
367         }
368     }
369
370   if (show_version)
371     {
372       printf ("head (%s) %s\n", GNU_PACKAGE, VERSION);
373       exit (EXIT_SUCCESS);
374     }
375
376   if (show_help)
377     usage (0);
378
379   if (header_mode == always
380       || (header_mode == multiple_files && optind < argc - 1))
381     print_headers = 1;
382
383   if (optind == argc)
384     exit_status |= head_file ("-", n_units, count_lines);
385
386   for (; optind < argc; ++optind)
387     exit_status |= head_file (argv[optind], n_units, count_lines);
388
389   if (have_read_stdin && close (0) < 0)
390     error (EXIT_FAILURE, errno, "-");
391   if (fclose (stdout) == EOF)
392     error (EXIT_FAILURE, errno, _("write error"));
393
394   exit (exit_status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
395 }