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