*** empty log message ***
[coreutils.git] / src / head.c
blobf0879a1d10f3f0bfd351c4165bf3743b6e1b0f6b
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)
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 "posixver.h"
36 #include "xstrtol.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. */
54 enum header_mode
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. */
63 char *program_name;
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},
77 {NULL, 0, NULL, 0}
80 void
81 usage (int status)
83 if (status != 0)
84 fprintf (stderr, _("Try `%s --help' for more information.\n"),
85 program_name);
86 else
88 printf (_("\
89 Usage: %s [OPTION]... [FILE]...\n\
90 "),
91 program_name);
92 fputs (_("\
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 "), stdout);
98 fputs (_("\
99 Mandatory arguments to long options are mandatory for short options too.\n\
100 "), stdout);
101 fputs (_("\
102 -c, --bytes=SIZE print first SIZE bytes\n\
103 -n, --lines=NUMBER print first NUMBER lines instead of first 10\n\
104 "), stdout);
105 fputs (_("\
106 -q, --quiet, --silent never print headers giving file names\n\
107 -v, --verbose always print headers giving file names\n\
108 "), stdout);
109 fputs (HELP_OPTION_DESCRIPTION, stdout);
110 fputs (VERSION_OPTION_DESCRIPTION, stdout);
111 fputs (_("\
113 SIZE may have a multiplier suffix: b for 512, k for 1K, m for 1 Meg.\n\
114 "), stdout);
115 printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
117 exit (status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
120 static void
121 write_header (const char *filename)
123 static int first_file = 1;
125 printf ("%s==> %s <==\n", (first_file ? "" : "\n"), filename);
126 first_file = 0;
129 static int
130 head_bytes (const char *filename, int fd, uintmax_t bytes_to_write)
132 char buffer[BUFSIZE];
133 int bytes_read;
134 size_t bytes_to_read = BUFSIZE;
136 /* Need BINARY I/O for the byte counts to be accurate. */
137 SET_BINARY2 (fd, fileno (stdout));
139 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 < 0)
146 error (0, errno, "%s", filename);
147 return 1;
149 if (bytes_read == 0)
150 break;
151 if (fwrite (buffer, 1, bytes_read, stdout) == 0)
152 error (EXIT_FAILURE, errno, _("write error"));
153 bytes_to_write -= bytes_read;
155 return 0;
158 static int
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 int bytes_read = safe_read (fd, buffer, BUFSIZE);
169 int bytes_to_write = 0;
171 if (bytes_read < 0)
173 error (0, errno, "%s", filename);
174 return 1;
176 if (bytes_read == 0)
177 break;
178 while (bytes_to_write < bytes_read)
179 if (buffer[bytes_to_write++] == '\n' && --lines_to_write == 0)
181 /* If we have read more data than that on the specified number
182 of lines, try to seek back to the position we would have
183 gotten to had we been reading one byte at a time. */
184 if (lseek (fd, bytes_to_write - bytes_read, SEEK_CUR) < 0)
186 int e = errno;
187 struct stat st;
188 if (fstat (fd, &st) != 0 || S_ISREG (st.st_mode))
189 error (0, e, _("cannot reposition file pointer for %s"),
190 filename);
192 break;
194 if (fwrite (buffer, 1, bytes_to_write, stdout) == 0)
195 error (EXIT_FAILURE, errno, _("write error"));
197 return 0;
200 static int
201 head (const char *filename, int fd, uintmax_t n_units, int count_lines)
203 if (print_headers)
204 write_header (filename);
206 if (count_lines)
207 return head_lines (filename, fd, n_units);
208 else
209 return head_bytes (filename, fd, n_units);
212 static int
213 head_file (const char *filename, uintmax_t n_units, int count_lines)
215 int fd;
217 if (STREQ (filename, "-"))
219 have_read_stdin = 1;
220 return head (_("standard input"), STDIN_FILENO, n_units, count_lines);
222 else
224 fd = open (filename, O_RDONLY);
225 if (fd >= 0)
227 int errors;
229 errors = head (filename, fd, n_units, count_lines);
230 if (close (fd) == 0)
231 return errors;
233 error (0, errno, "%s", filename);
234 return 1;
238 /* Convert a string of decimal digits, N_STRING, with a single, optional suffix
239 character (b, k, or m) to an integral value. Upon successful conversion,
240 return that value. If it cannot be converted, give a diagnostic and exit.
241 COUNT_LINES indicates whether N_STRING is a number of bytes or a number
242 of lines. It is used solely to give a more specific diagnostic. */
244 static uintmax_t
245 string_to_integer (int count_lines, const char *n_string)
247 strtol_error s_err;
248 uintmax_t n;
250 s_err = xstrtoumax (n_string, NULL, 10, &n, "bkm");
252 if (s_err == LONGINT_OVERFLOW)
254 error (EXIT_FAILURE, 0,
255 _("%s: %s is so large that it is not representable"), n_string,
256 count_lines ? _("number of lines") : _("number of bytes"));
259 if (s_err != LONGINT_OK)
261 error (EXIT_FAILURE, 0, "%s: %s", n_string,
262 (count_lines
263 ? _("invalid number of lines")
264 : _("invalid number of bytes")));
267 return n;
271 main (int argc, char **argv)
273 enum header_mode header_mode = multiple_files;
274 int exit_status = 0;
275 int c;
277 /* Number of items to print. */
278 uintmax_t n_units = DEFAULT_NUMBER;
280 /* If nonzero, interpret the numeric argument as the number of lines.
281 Otherwise, interpret it as the number of bytes. */
282 int count_lines = 1;
284 program_name = argv[0];
285 setlocale (LC_ALL, "");
286 bindtextdomain (PACKAGE, LOCALEDIR);
287 textdomain (PACKAGE);
289 atexit (close_stdout);
291 have_read_stdin = 0;
293 print_headers = 0;
295 if (1 < argc && argv[1][0] == '-' && ISDIGIT (argv[1][1]))
297 char *a = argv[1];
298 char *n_string = ++a;
299 char *end_n_string;
300 char multiplier_char = 0;
302 /* Old option syntax; a dash, one or more digits, and one or
303 more option letters. Move past the number. */
304 do ++a;
305 while (ISDIGIT (*a));
307 /* Pointer to the byte after the last digit. */
308 end_n_string = a;
310 /* Parse any appended option letters. */
311 for (; *a; a++)
313 switch (*a)
315 case 'c':
316 count_lines = 0;
317 multiplier_char = 0;
318 break;
320 case 'b':
321 case 'k':
322 case 'm':
323 count_lines = 0;
324 multiplier_char = *a;
325 break;
327 case 'l':
328 count_lines = 1;
329 break;
331 case 'q':
332 header_mode = never;
333 break;
335 case 'v':
336 header_mode = always;
337 break;
339 default:
340 error (0, 0, _("unrecognized option `-%c'"), *a);
341 usage (1);
345 if (200112 <= posix2_version ())
347 error (0, 0, _("`-%s' option is obsolete; use `-%c %.*s%.*s%s'"),
348 n_string, count_lines ? 'n' : 'c',
349 (int) (end_n_string - n_string), n_string,
350 multiplier_char != 0, &multiplier_char,
351 header_mode_option[header_mode]);
352 usage (EXIT_FAILURE);
355 /* Append the multiplier character (if any) onto the end of
356 the digit string. Then add NUL byte if necessary. */
357 *end_n_string = multiplier_char;
358 if (multiplier_char)
359 *(++end_n_string) = 0;
361 n_units = string_to_integer (count_lines, n_string);
363 /* Make the options we just parsed invisible to getopt. */
364 argv[1] = argv[0];
365 argv++;
366 argc--;
368 /* FIXME: allow POSIX options if there were obsolescent ones? */
372 while ((c = getopt_long (argc, argv, "c:n:qv", long_options, NULL)) != -1)
374 switch (c)
376 case 0:
377 break;
379 case 'c':
380 count_lines = 0;
381 n_units = string_to_integer (count_lines, optarg);
382 break;
384 case 'n':
385 count_lines = 1;
386 n_units = string_to_integer (count_lines, optarg);
387 break;
389 case 'q':
390 header_mode = never;
391 break;
393 case 'v':
394 header_mode = always;
395 break;
397 case_GETOPT_HELP_CHAR;
399 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
401 default:
402 usage (1);
406 if (header_mode == always
407 || (header_mode == multiple_files && optind < argc - 1))
408 print_headers = 1;
410 if (optind == argc)
411 exit_status |= head_file ("-", n_units, count_lines);
413 for (; optind < argc; ++optind)
414 exit_status |= head_file (argv[optind], n_units, count_lines);
416 if (have_read_stdin && close (STDIN_FILENO) < 0)
417 error (EXIT_FAILURE, errno, "-");
419 exit (exit_status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);