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