(jm_FILE_SYSTEM_USAGE): Add `[]' between use of
[coreutils.git] / src / head.c
blob7bc3cad17a4909e6303d36bcefe3d4ec8222da0f
1 /* head -- output first part of file(s)
2 Copyright (C) 89, 90, 91, 1995-2000 Free Software Foundation, Inc.
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.
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.
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. */
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).
25 David MacKenzie <djm@gnu.ai.mit.edu> */
27 #include <config.h>
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"
38 /* The official name of this program (e.g., no `g' prefix). */
39 #define PROGRAM_NAME "head"
41 #define AUTHORS "David MacKenzie"
43 /* Number of lines/chars/blocks to head. */
44 #define DEFAULT_NUMBER 10
46 /* Size of atomic reads. */
47 #define BUFSIZE (512 * 8)
49 /* If nonzero, print filename headers. */
50 static int print_headers;
52 /* When to print the filename banners. */
53 enum header_mode
55 multiple_files, always, never
58 /* The name this program was run with. */
59 char *program_name;
61 /* Have we ever read standard input? */
62 static int have_read_stdin;
64 static struct option const long_options[] =
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}
76 void
77 usage (int status)
79 if (status != 0)
80 fprintf (stderr, _("Try `%s --help' for more information.\n"),
81 program_name);
82 else
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 -c, --bytes=SIZE print first SIZE bytes\n\
94 -n, --lines=NUMBER print first NUMBER lines instead of first 10\n\
95 -q, --quiet, --silent never print headers giving file names\n\
96 -v, --verbose always print headers giving file names\n\
97 --help display this help and exit\n\
98 --version output version information and exit\n\
99 \n\
100 SIZE may have a multiplier suffix: b for 512, k for 1K, m for 1 Meg.\n\
101 If -VALUE is used as first OPTION, read -c VALUE when one of\n\
102 multipliers bkm follows concatenated, else read -n VALUE.\n\
103 "));
104 puts (_("\nReport bugs to <bug-textutils@gnu.org>."));
106 exit (status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
109 static void
110 write_header (const char *filename)
112 static int first_file = 1;
114 printf ("%s==> %s <==\n", (first_file ? "" : "\n"), filename);
115 first_file = 0;
118 static int
119 head_bytes (const char *filename, int fd, uintmax_t bytes_to_write)
121 char buffer[BUFSIZE];
122 int bytes_read;
124 /* Need BINARY I/O for the byte counts to be accurate. */
125 SET_BINARY2 (fd, fileno (stdout));
127 while (bytes_to_write)
129 bytes_read = safe_read (fd, buffer, BUFSIZE);
130 if (bytes_read < 0)
132 error (0, errno, "%s", filename);
133 return 1;
135 if (bytes_read == 0)
136 break;
137 if (bytes_read > bytes_to_write)
138 bytes_read = bytes_to_write;
139 if (fwrite (buffer, 1, bytes_read, stdout) == 0)
140 error (EXIT_FAILURE, errno, _("write error"));
141 bytes_to_write -= bytes_read;
143 return 0;
146 static int
147 head_lines (const char *filename, int fd, uintmax_t lines_to_write)
149 char buffer[BUFSIZE];
151 /* Need BINARY I/O for the byte counts to be accurate. */
152 SET_BINARY2 (fd, fileno (stdout));
154 while (lines_to_write)
156 int bytes_read = safe_read (fd, buffer, BUFSIZE);
157 int bytes_to_write = 0;
159 if (bytes_read < 0)
161 error (0, errno, "%s", filename);
162 return 1;
164 if (bytes_read == 0)
165 break;
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"));
172 return 0;
175 static int
176 head (const char *filename, int fd, uintmax_t n_units, int count_lines)
178 if (print_headers)
179 write_header (filename);
181 if (count_lines)
182 return head_lines (filename, fd, n_units);
183 else
184 return head_bytes (filename, fd, n_units);
187 static int
188 head_file (const char *filename, uintmax_t n_units, int count_lines)
190 int fd;
192 if (STREQ (filename, "-"))
194 have_read_stdin = 1;
195 return head (_("standard input"), STDIN_FILENO, n_units, count_lines);
197 else
199 fd = open (filename, O_RDONLY);
200 if (fd >= 0)
202 int errors;
204 errors = head (filename, fd, n_units, count_lines);
205 if (close (fd) == 0)
206 return errors;
208 error (0, errno, "%s", filename);
209 return 1;
213 /* Convert a string of decimal digits, N_STRING, with a single, optional suffix
214 character (b, k, or m) to an integral value. Upon successful conversion,
215 return that value. If it cannot be converted, give a diagnostic and exit.
216 COUNT_LINES indicates whether N_STRING is a number of bytes or a number
217 of lines. It is used solely to give a more specific diagnostic. */
219 static uintmax_t
220 string_to_integer (int count_lines, const char *n_string)
222 strtol_error s_err;
223 uintmax_t n;
225 s_err = xstrtoumax (n_string, NULL, 10, &n, "bkm");
227 if (s_err == LONGINT_INVALID)
229 error (EXIT_FAILURE, 0, "%s: %s", n_string,
230 (count_lines
231 ? _("invalid number of lines")
232 : _("invalid number of bytes")));
235 if (s_err != LONGINT_OK)
237 error (EXIT_FAILURE, 0,
238 _("%s: %s is so large that it is not representable"), n_string,
239 count_lines ? _("number of lines") : _("number of bytes"));
242 return n;
246 main (int argc, char **argv)
248 enum header_mode header_mode = multiple_files;
249 int exit_status = 0;
250 char *n_string;
251 int c;
253 /* Number of items to print. */
254 uintmax_t n_units = DEFAULT_NUMBER;
256 /* If nonzero, interpret the numeric argument as the number of lines.
257 Otherwise, interpret it as the number of bytes. */
258 int count_lines = 1;
260 program_name = argv[0];
261 setlocale (LC_ALL, "");
262 bindtextdomain (PACKAGE, LOCALEDIR);
263 textdomain (PACKAGE);
265 atexit (close_stdout);
267 have_read_stdin = 0;
269 print_headers = 0;
271 if (argc > 1 && argv[1][0] == '-' && ISDIGIT (argv[1][1]))
273 char *end_n_string;
274 char multiplier_char = 0;
276 n_string = &argv[1][1];
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])
282 /* empty */
285 /* Pointer to the byte after the last digit. */
286 end_n_string = argv[1];
288 /* Parse any appended option letters. */
289 while (*argv[1])
291 switch (*argv[1])
293 case 'c':
294 count_lines = 0;
295 multiplier_char = 0;
296 break;
298 case 'b':
299 case 'k':
300 case 'm':
301 count_lines = 0;
302 multiplier_char = *argv[1];
303 break;
305 case 'l':
306 count_lines = 1;
307 break;
309 case 'q':
310 header_mode = never;
311 break;
313 case 'v':
314 header_mode = always;
315 break;
317 default:
318 error (0, 0, _("unrecognized option `-%c'"), *argv[1]);
319 usage (1);
321 ++argv[1];
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;
330 n_units = string_to_integer (count_lines, n_string);
332 /* Make the options we just parsed invisible to getopt. */
333 argv[1] = argv[0];
334 argv++;
335 argc--;
337 /* FIXME: allow POSIX options if there were obsolescent ones? */
341 while ((c = getopt_long (argc, argv, "c:n:qv", long_options, NULL)) != -1)
343 switch (c)
345 case 0:
346 break;
348 case 'c':
349 count_lines = 0;
350 n_units = string_to_integer (count_lines, optarg);
351 break;
353 case 'n':
354 count_lines = 1;
355 n_units = string_to_integer (count_lines, optarg);
356 break;
358 case 'q':
359 header_mode = never;
360 break;
362 case 'v':
363 header_mode = always;
364 break;
366 case_GETOPT_HELP_CHAR;
368 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
370 default:
371 usage (1);
375 if (header_mode == always
376 || (header_mode == multiple_files && optind < argc - 1))
377 print_headers = 1;
379 if (optind == argc)
380 exit_status |= head_file ("-", n_units, count_lines);
382 for (; optind < argc; ++optind)
383 exit_status |= head_file (argv[optind], n_units, count_lines);
385 if (have_read_stdin && close (STDIN_FILENO) < 0)
386 error (EXIT_FAILURE, errno, "-");
388 exit (exit_status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);