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