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