ad03cdd4a338dae2147f043e614aff9072572a74
[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 "long-options.h"
35 #include "xstrtoul.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 /* FIXME: someday, make this really *be* `long long'.  */
42 typedef long int U_LONG_LONG;
43
44 /* Number of lines/chars/blocks to head. */
45 #define DEFAULT_NUMBER 10
46
47 /* Size of atomic reads. */
48 #define BUFSIZE (512 * 8)
49
50 /* If nonzero, print filename headers. */
51 static int print_headers;
52
53 /* When to print the filename banners. */
54 enum header_mode
55 {
56   multiple_files, always, never
57 };
58
59 /* The name this program was run with. */
60 char *program_name;
61
62 /* Have we ever read standard input?  */
63 static int have_read_stdin;
64
65 static struct option const long_options[] =
66 {
67   {"bytes", required_argument, NULL, 'c'},
68   {"lines", required_argument, NULL, 'n'},
69   {"quiet", no_argument, NULL, 'q'},
70   {"silent", no_argument, NULL, 'q'},
71   {"verbose", no_argument, NULL, 'v'},
72   {NULL, 0, NULL, 0}
73 };
74
75 void
76 usage (int status)
77 {
78   if (status != 0)
79     fprintf (stderr, _("Try `%s --help' for more information.\n"),
80              program_name);
81   else
82     {
83       printf (_("\
84 Usage: %s [OPTION]... [FILE]...\n\
85 "),
86               program_name);
87       printf (_("\
88 Print first 10 lines of each FILE to standard output.\n\
89 With more than one FILE, precede each with a header giving the file name.\n\
90 With no FILE, or when FILE is -, read standard input.\n\
91 \n\
92   -c, --bytes=SIZE         print first SIZE bytes\n\
93   -n, --lines=NUMBER       print first NUMBER lines instead of first 10\n\
94   -q, --quiet, --silent    never print headers giving file names\n\
95   -v, --verbose            always print headers giving file names\n\
96       --help               display this help and exit\n\
97       --version            output version information and exit\n\
98 \n\
99 SIZE may have a multiplier suffix: b for 512, k for 1K, m for 1 Meg.\n\
100 If -VALUE is used as first OPTION, read -c VALUE when one of\n\
101 multipliers bkm follows concatenated, else read -n VALUE.\n\
102 "));
103       puts (_("\nReport bugs to <bug-textutils@gnu.org>."));
104     }
105   exit (status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
106 }
107
108 static void
109 write_header (const char *filename)
110 {
111   static int first_file = 1;
112
113   printf ("%s==> %s <==\n", (first_file ? "" : "\n"), filename);
114   first_file = 0;
115 }
116
117 static int
118 head_bytes (const char *filename, int fd, U_LONG_LONG bytes_to_write)
119 {
120   char buffer[BUFSIZE];
121   int bytes_read;
122
123   /* Need BINARY I/O for the byte counts to be accurate.  */
124   SET_BINARY2 (fd, fileno (stdout));
125
126   while (bytes_to_write)
127     {
128       bytes_read = safe_read (fd, buffer, BUFSIZE);
129       if (bytes_read < 0)
130         {
131           error (0, errno, "%s", filename);
132           return 1;
133         }
134       if (bytes_read == 0)
135         break;
136       if (bytes_read > bytes_to_write)
137         bytes_read = bytes_to_write;
138       if (fwrite (buffer, 1, bytes_read, stdout) == 0)
139         error (EXIT_FAILURE, errno, _("write error"));
140       bytes_to_write -= bytes_read;
141     }
142   return 0;
143 }
144
145 static int
146 head_lines (const char *filename, int fd, U_LONG_LONG lines_to_write)
147 {
148   char buffer[BUFSIZE];
149   int bytes_read;
150   int bytes_to_write;
151
152   /* Need BINARY I/O for the byte counts to be accurate.  */
153   SET_BINARY2 (fd, fileno (stdout));
154
155   while (lines_to_write)
156     {
157       bytes_read = safe_read (fd, buffer, BUFSIZE);
158       if (bytes_read < 0)
159         {
160           error (0, errno, "%s", filename);
161           return 1;
162         }
163       if (bytes_read == 0)
164         break;
165       bytes_to_write = 0;
166       while (bytes_to_write < bytes_read)
167         if (buffer[bytes_to_write++] == '\n' && --lines_to_write == 0)
168           break;
169       if (fwrite (buffer, 1, bytes_to_write, stdout) == 0)
170         error (EXIT_FAILURE, errno, _("write error"));
171     }
172   return 0;
173 }
174
175 static int
176 head (const char *filename, int fd, U_LONG_LONG n_units, int count_lines)
177 {
178   if (count_lines)
179     return head_lines (filename, fd, n_units);
180   else
181     return head_bytes (filename, fd, n_units);
182 }
183
184 static int
185 head_file (const char *filename, U_LONG_LONG n_units, int count_lines)
186 {
187   int fd;
188
189   if (STREQ (filename, "-"))
190     {
191       have_read_stdin = 1;
192       filename = _("standard input");
193       if (print_headers)
194         write_header (filename);
195       return head (filename, 0, n_units, count_lines);
196     }
197   else
198     {
199       fd = open (filename, O_RDONLY);
200       if (fd >= 0)
201         {
202           int errors;
203
204           if (print_headers)
205             write_header (filename);
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 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 U_LONG_LONG
222 string_to_ull (int count_lines, const char *n_string)
223 {
224   strtol_error s_err;
225   unsigned long int tmp_ulong;
226
227   s_err = xstrtoul (n_string, NULL, 0, &tmp_ulong, "bkm");
228
229   if (s_err == LONGINT_INVALID)
230     {
231       error (EXIT_FAILURE, 0, "%s: %s", n_string,
232              (count_lines
233               ? _("invalid number of lines")
234               : _("invalid number of bytes")));
235     }
236
237   if (s_err != LONGINT_OK)
238     {
239       error (EXIT_FAILURE, 0,
240              _("%s: %s is so large that it is not representable"), n_string,
241              count_lines ? _("number of lines") : _("number of bytes"));
242     }
243
244   return tmp_ulong;
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   U_LONG_LONG 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   parse_long_options (argc, argv, "head", GNU_PACKAGE, VERSION,
268                       "David MacKenzie", usage);
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         default:
370           usage (1);
371         }
372     }
373
374   if (header_mode == always
375       || (header_mode == multiple_files && optind < argc - 1))
376     print_headers = 1;
377
378   if (optind == argc)
379     exit_status |= head_file ("-", n_units, count_lines);
380
381   for (; optind < argc; ++optind)
382     exit_status |= head_file (argv[optind], n_units, count_lines);
383
384   if (have_read_stdin && close (0) < 0)
385     error (EXIT_FAILURE, errno, "-");
386   if (fclose (stdout) == EOF)
387     error (EXIT_FAILURE, errno, _("write error"));
388
389   exit (exit_status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
390 }