1 /* head -- output first part of file(s)
2 Copyright (C) 89, 90, 91, 1995-2002 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)
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
21 By default, filename headers are printed only if more than one file
23 By default, prints the first 10 lines (head -n 10).
25 David MacKenzie <djm@gnu.ai.mit.edu> */
31 #include <sys/types.h>
37 #include "safe-read.h"
39 /* The official name of this program (e.g., no `g' prefix). */
40 #define PROGRAM_NAME "head"
42 #define AUTHORS "David MacKenzie"
44 /* Number of lines/chars/blocks to head. */
45 #define DEFAULT_NUMBER 10
47 /* Size of atomic reads. */
48 #define BUFSIZE (512 * 8)
50 /* If nonzero, print filename headers. */
51 static int print_headers;
53 /* When to print the filename banners. */
56 multiple_files, always, never
59 /* Options corresponding to header_mode values. */
60 static char const header_mode_option[][4] = { "", " -v", " -q" };
62 /* The name this program was run with. */
65 /* Have we ever read standard input? */
66 static int have_read_stdin;
68 static struct option const long_options[] =
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 {GETOPT_HELP_OPTION_DECL},
76 {GETOPT_VERSION_OPTION_DECL},
84 fprintf (stderr, _("Try `%s --help' for more information.\n"),
89 Usage: %s [OPTION]... [FILE]...\n\
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\
99 Mandatory arguments to long options are mandatory for short options too.\n\
102 -c, --bytes=SIZE print first SIZE bytes\n\
103 -n, --lines=NUMBER print first NUMBER lines instead of first 10\n\
106 -q, --quiet, --silent never print headers giving file names\n\
107 -v, --verbose always print headers giving file names\n\
109 fputs (HELP_OPTION_DESCRIPTION, stdout);
110 fputs (VERSION_OPTION_DESCRIPTION, stdout);
113 SIZE may have a multiplier suffix: b for 512, k for 1K, m for 1 Meg.\n\
115 printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
117 exit (status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
121 write_header (const char *filename)
123 static int first_file = 1;
125 printf ("%s==> %s <==\n", (first_file ? "" : "\n"), filename);
130 head_bytes (const char *filename, int fd, uintmax_t bytes_to_write)
132 char buffer[BUFSIZE];
133 size_t bytes_to_read = BUFSIZE;
135 /* Need BINARY I/O for the byte counts to be accurate. */
136 SET_BINARY2 (fd, fileno (stdout));
138 while (bytes_to_write)
141 if (bytes_to_write < bytes_to_read)
142 bytes_to_read = bytes_to_write;
143 bytes_read = safe_read (fd, buffer, bytes_to_read);
144 if (bytes_read == SAFE_READ_ERROR)
146 error (0, errno, "%s", filename);
151 if (fwrite (buffer, 1, bytes_read, stdout) == 0)
152 error (EXIT_FAILURE, errno, _("write error"));
153 bytes_to_write -= bytes_read;
159 head_lines (const char *filename, int fd, uintmax_t lines_to_write)
161 char buffer[BUFSIZE];
163 /* Need BINARY I/O for the byte counts to be accurate. */
164 SET_BINARY2 (fd, fileno (stdout));
166 while (lines_to_write)
168 size_t bytes_read = safe_read (fd, buffer, BUFSIZE);
169 size_t bytes_to_write = 0;
171 if (bytes_read == SAFE_READ_ERROR)
173 error (0, errno, "%s", filename);
178 while (bytes_to_write < bytes_read)
179 if (buffer[bytes_to_write++] == '\n' && --lines_to_write == 0)
181 off_t n_bytes_past_EOL = bytes_read - bytes_to_write;
182 /* If we have read more data than that on the specified number
183 of lines, try to seek back to the position we would have
184 gotten to had we been reading one byte at a time. */
185 if (lseek (fd, -n_bytes_past_EOL, SEEK_CUR) < 0)
189 if (fstat (fd, &st) != 0 || S_ISREG (st.st_mode))
190 error (0, e, _("cannot reposition file pointer for %s"),
195 if (fwrite (buffer, 1, bytes_to_write, stdout) == 0)
196 error (EXIT_FAILURE, errno, _("write error"));
202 head (const char *filename, int fd, uintmax_t n_units, int count_lines)
205 write_header (filename);
208 return head_lines (filename, fd, n_units);
210 return head_bytes (filename, fd, n_units);
214 head_file (const char *filename, uintmax_t n_units, int count_lines)
218 if (STREQ (filename, "-"))
221 return head (_("standard input"), STDIN_FILENO, n_units, count_lines);
225 fd = open (filename, O_RDONLY);
230 errors = head (filename, fd, n_units, count_lines);
234 error (0, errno, "%s", filename);
239 /* Convert a string of decimal digits, N_STRING, with a single, optional suffix
240 character (b, k, or m) to an integral value. Upon successful conversion,
241 return that value. If it cannot be converted, give a diagnostic and exit.
242 COUNT_LINES indicates whether N_STRING is a number of bytes or a number
243 of lines. It is used solely to give a more specific diagnostic. */
246 string_to_integer (int count_lines, const char *n_string)
251 s_err = xstrtoumax (n_string, NULL, 10, &n, "bkm");
253 if (s_err == LONGINT_OVERFLOW)
255 error (EXIT_FAILURE, 0,
256 _("%s: %s is so large that it is not representable"), n_string,
257 count_lines ? _("number of lines") : _("number of bytes"));
260 if (s_err != LONGINT_OK)
262 error (EXIT_FAILURE, 0, "%s: %s", n_string,
264 ? _("invalid number of lines")
265 : _("invalid number of bytes")));
272 main (int argc, char **argv)
274 enum header_mode header_mode = multiple_files;
278 /* Number of items to print. */
279 uintmax_t n_units = DEFAULT_NUMBER;
281 /* If nonzero, interpret the numeric argument as the number of lines.
282 Otherwise, interpret it as the number of bytes. */
285 program_name = argv[0];
286 setlocale (LC_ALL, "");
287 bindtextdomain (PACKAGE, LOCALEDIR);
288 textdomain (PACKAGE);
290 atexit (close_stdout);
296 if (1 < argc && argv[1][0] == '-' && ISDIGIT (argv[1][1]))
299 char *n_string = ++a;
301 char multiplier_char = 0;
303 /* Old option syntax; a dash, one or more digits, and one or
304 more option letters. Move past the number. */
306 while (ISDIGIT (*a));
308 /* Pointer to the byte after the last digit. */
311 /* Parse any appended option letters. */
325 multiplier_char = *a;
337 header_mode = always;
341 error (0, 0, _("unrecognized option `-%c'"), *a);
342 usage (EXIT_FAILURE);
346 if (200112 <= posix2_version ())
348 error (0, 0, _("`-%s' option is obsolete; use `-%c %.*s%.*s%s'"),
349 n_string, count_lines ? 'n' : 'c',
350 (int) (end_n_string - n_string), n_string,
351 multiplier_char != 0, &multiplier_char,
352 header_mode_option[header_mode]);
353 usage (EXIT_FAILURE);
356 /* Append the multiplier character (if any) onto the end of
357 the digit string. Then add NUL byte if necessary. */
358 *end_n_string = multiplier_char;
360 *(++end_n_string) = 0;
362 n_units = string_to_integer (count_lines, n_string);
364 /* Make the options we just parsed invisible to getopt. */
369 /* FIXME: allow POSIX options if there were obsolescent ones? */
373 while ((c = getopt_long (argc, argv, "c:n:qv", long_options, NULL)) != -1)
382 n_units = string_to_integer (count_lines, optarg);
387 n_units = string_to_integer (count_lines, optarg);
395 header_mode = always;
398 case_GETOPT_HELP_CHAR;
400 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
403 usage (EXIT_FAILURE);
407 if (header_mode == always
408 || (header_mode == multiple_files && optind < argc - 1))
412 exit_status |= head_file ("-", n_units, count_lines);
414 for (; optind < argc; ++optind)
415 exit_status |= head_file (argv[optind], n_units, count_lines);
417 if (have_read_stdin && close (STDIN_FILENO) < 0)
418 error (EXIT_FAILURE, errno, "-");
420 exit (exit_status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);