3a8049351adc9a5550d53e9dd8ba9353d450183c
[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       fputs (_("\
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 "), stdout);
97       fputs (_("\
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 "), stdout);
107       puts (_("\nReport bugs to <bug-textutils@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, uintmax_t bytes_to_write)
123 {
124   char buffer[BUFSIZE];
125   int bytes_read;
126   size_t bytes_to_read = BUFSIZE;
127
128   /* Need BINARY I/O for the byte counts to be accurate.  */
129   SET_BINARY2 (fd, fileno (stdout));
130
131   while (bytes_to_write)
132     {
133       if (bytes_to_write < bytes_to_read)
134         bytes_to_read = bytes_to_write;
135       bytes_read = safe_read (fd, buffer, bytes_to_read);
136       if (bytes_read < 0)
137         {
138           error (0, errno, "%s", filename);
139           return 1;
140         }
141       if (bytes_read == 0)
142         break;
143       if (fwrite (buffer, 1, bytes_read, stdout) == 0)
144         error (EXIT_FAILURE, errno, _("write error"));
145       bytes_to_write -= bytes_read;
146     }
147   return 0;
148 }
149
150 static int
151 head_lines (const char *filename, int fd, uintmax_t lines_to_write)
152 {
153   char buffer[BUFSIZE];
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       int bytes_read = safe_read (fd, buffer, BUFSIZE);
161       int bytes_to_write = 0;
162
163       if (bytes_read < 0)
164         {
165           error (0, errno, "%s", filename);
166           return 1;
167         }
168       if (bytes_read == 0)
169         break;
170       while (bytes_to_write < bytes_read)
171         if (buffer[bytes_to_write++] == '\n' && --lines_to_write == 0)
172           break;
173       if (fwrite (buffer, 1, bytes_to_write, stdout) == 0)
174         error (EXIT_FAILURE, errno, _("write error"));
175     }
176   return 0;
177 }
178
179 static int
180 head (const char *filename, int fd, uintmax_t n_units, int count_lines)
181 {
182   if (print_headers)
183     write_header (filename);
184
185   if (count_lines)
186     return head_lines (filename, fd, n_units);
187   else
188     return head_bytes (filename, fd, n_units);
189 }
190
191 static int
192 head_file (const char *filename, uintmax_t n_units, int count_lines)
193 {
194   int fd;
195
196   if (STREQ (filename, "-"))
197     {
198       have_read_stdin = 1;
199       return head (_("standard input"), STDIN_FILENO, n_units, count_lines);
200     }
201   else
202     {
203       fd = open (filename, O_RDONLY);
204       if (fd >= 0)
205         {
206           int errors;
207
208           errors = head (filename, fd, n_units, count_lines);
209           if (close (fd) == 0)
210             return errors;
211         }
212       error (0, errno, "%s", filename);
213       return 1;
214     }
215 }
216
217 /* Convert a string of decimal digits, N_STRING, with a single, optional suffix
218    character (b, k, or m) to an integral value.  Upon successful conversion,
219    return that value.  If it cannot be converted, give a diagnostic and exit.
220    COUNT_LINES indicates whether N_STRING is a number of bytes or a number
221    of lines.  It is used solely to give a more specific diagnostic.  */
222
223 static uintmax_t
224 string_to_integer (int count_lines, const char *n_string)
225 {
226   strtol_error s_err;
227   uintmax_t n;
228
229   s_err = xstrtoumax (n_string, NULL, 10, &n, "bkm");
230
231   if (s_err == LONGINT_OVERFLOW)
232     {
233       error (EXIT_FAILURE, 0,
234              _("%s: %s is so large that it is not representable"), n_string,
235              count_lines ? _("number of lines") : _("number of bytes"));
236     }
237
238   if (s_err != LONGINT_OK)
239     {
240       error (EXIT_FAILURE, 0, "%s: %s", n_string,
241              (count_lines
242               ? _("invalid number of lines")
243               : _("invalid number of bytes")));
244     }
245
246   return n;
247 }
248
249 int
250 main (int argc, char **argv)
251 {
252   enum header_mode header_mode = multiple_files;
253   int exit_status = 0;
254   char *n_string;
255   int c;
256
257   /* Number of items to print. */
258   uintmax_t n_units = DEFAULT_NUMBER;
259
260   /* If nonzero, interpret the numeric argument as the number of lines.
261      Otherwise, interpret it as the number of bytes.  */
262   int count_lines = 1;
263
264   program_name = argv[0];
265   setlocale (LC_ALL, "");
266   bindtextdomain (PACKAGE, LOCALEDIR);
267   textdomain (PACKAGE);
268
269   atexit (close_stdout);
270
271   have_read_stdin = 0;
272
273   print_headers = 0;
274
275   if (argc > 1 && argv[1][0] == '-' && ISDIGIT (argv[1][1]))
276     {
277       char *end_n_string;
278       char multiplier_char = 0;
279
280       n_string = &argv[1][1];
281
282       /* Old option syntax; a dash, one or more digits, and one or
283          more option letters.  Move past the number. */
284       for (++argv[1]; ISDIGIT (*argv[1]); ++argv[1])
285         {
286           /* empty */
287         }
288
289       /* Pointer to the byte after the last digit.  */
290       end_n_string = argv[1];
291
292       /* Parse any appended option letters. */
293       while (*argv[1])
294         {
295           switch (*argv[1])
296             {
297             case 'c':
298               count_lines = 0;
299               multiplier_char = 0;
300               break;
301
302             case 'b':
303             case 'k':
304             case 'm':
305               count_lines = 0;
306               multiplier_char = *argv[1];
307               break;
308
309             case 'l':
310               count_lines = 1;
311               break;
312
313             case 'q':
314               header_mode = never;
315               break;
316
317             case 'v':
318               header_mode = always;
319               break;
320
321             default:
322               error (0, 0, _("unrecognized option `-%c'"), *argv[1]);
323               usage (1);
324             }
325           ++argv[1];
326         }
327
328       /* Append the multiplier character (if any) onto the end of
329          the digit string.  Then add NUL byte if necessary.  */
330       *end_n_string = multiplier_char;
331       if (multiplier_char)
332         *(++end_n_string) = 0;
333
334       n_units = string_to_integer (count_lines, n_string);
335
336       /* Make the options we just parsed invisible to getopt. */
337       argv[1] = argv[0];
338       argv++;
339       argc--;
340
341       /* FIXME: allow POSIX options if there were obsolescent ones?  */
342
343     }
344
345   while ((c = getopt_long (argc, argv, "c:n:qv", long_options, NULL)) != -1)
346     {
347       switch (c)
348         {
349         case 0:
350           break;
351
352         case 'c':
353           count_lines = 0;
354           n_units = string_to_integer (count_lines, optarg);
355           break;
356
357         case 'n':
358           count_lines = 1;
359           n_units = string_to_integer (count_lines, optarg);
360           break;
361
362         case 'q':
363           header_mode = never;
364           break;
365
366         case 'v':
367           header_mode = always;
368           break;
369
370         case_GETOPT_HELP_CHAR;
371
372         case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
373
374         default:
375           usage (1);
376         }
377     }
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 (STDIN_FILENO) < 0)
390     error (EXIT_FAILURE, errno, "-");
391
392   exit (exit_status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
393 }