ls: --color now highlights hard linked files, too
[coreutils/bo.git] / src / head.c
blob0ef912a58c7f0c545fe3bd0516f91c8f55a11974
1 /* head -- output first part of file(s)
2 Copyright (C) 89, 90, 91, 1995-2006, 2008 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 3 of the License, or
7 (at your option) 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, see <http://www.gnu.org/licenses/>. */
17 /* Options: (see usage)
18 Reads from standard input if no files are given or when a filename of
19 ``-'' is encountered.
20 By default, filename headers are printed only if more than one file
21 is given.
22 By default, prints the first 10 lines (head -n 10).
24 David MacKenzie <djm@gnu.ai.mit.edu> */
26 #include <config.h>
28 #include <stdio.h>
29 #include <getopt.h>
30 #include <sys/types.h>
32 #include "system.h"
34 #include "error.h"
35 #include "full-write.h"
36 #include "full-read.h"
37 #include "quote.h"
38 #include "safe-read.h"
39 #include "xstrtol.h"
41 /* The official name of this program (e.g., no `g' prefix). */
42 #define PROGRAM_NAME "head"
44 #define AUTHORS \
45 proper_name ("David MacKenzie"), \
46 proper_name ("Jim Meyering")
48 /* Number of lines/chars/blocks to head. */
49 #define DEFAULT_NUMBER 10
51 /* Useful only when eliding tail bytes or lines.
52 If true, skip the is-regular-file test used to determine whether
53 to use the lseek optimization. Instead, use the more general (and
54 more expensive) code unconditionally. Intended solely for testing. */
55 static bool presume_input_pipe;
57 /* If true, print filename headers. */
58 static bool print_headers;
60 /* When to print the filename banners. */
61 enum header_mode
63 multiple_files, always, never
66 /* Have we ever read standard input? */
67 static bool have_read_stdin;
69 enum Copy_fd_status
71 COPY_FD_OK = 0,
72 COPY_FD_READ_ERROR,
73 COPY_FD_WRITE_ERROR,
74 COPY_FD_UNEXPECTED_EOF
77 /* For long options that have no equivalent short option, use a
78 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
79 enum
81 PRESUME_INPUT_PIPE_OPTION = CHAR_MAX + 1
84 static struct option const long_options[] =
86 {"bytes", required_argument, NULL, 'c'},
87 {"lines", required_argument, NULL, 'n'},
88 {"-presume-input-pipe", no_argument, NULL,
89 PRESUME_INPUT_PIPE_OPTION}, /* do not document */
90 {"quiet", no_argument, NULL, 'q'},
91 {"silent", no_argument, NULL, 'q'},
92 {"verbose", no_argument, NULL, 'v'},
93 {GETOPT_HELP_OPTION_DECL},
94 {GETOPT_VERSION_OPTION_DECL},
95 {NULL, 0, NULL, 0}
98 void
99 usage (int status)
101 if (status != EXIT_SUCCESS)
102 fprintf (stderr, _("Try `%s --help' for more information.\n"),
103 program_name);
104 else
106 printf (_("\
107 Usage: %s [OPTION]... [FILE]...\n\
109 program_name);
110 fputs (_("\
111 Print the first 10 lines of each FILE to standard output.\n\
112 With more than one FILE, precede each with a header giving the file name.\n\
113 With no FILE, or when FILE is -, read standard input.\n\
115 "), stdout);
116 fputs (_("\
117 Mandatory arguments to long options are mandatory for short options too.\n\
118 "), stdout);
119 fputs (_("\
120 -c, --bytes=[-]N print the first N bytes of each file;\n\
121 with the leading `-', print all but the last\n\
122 N bytes of each file\n\
123 -n, --lines=[-]N print the first N lines instead of the first 10;\n\
124 with the leading `-', print all but the last\n\
125 N lines of each file\n\
126 "), stdout);
127 fputs (_("\
128 -q, --quiet, --silent never print headers giving file names\n\
129 -v, --verbose always print headers giving file names\n\
130 "), stdout);
131 fputs (HELP_OPTION_DESCRIPTION, stdout);
132 fputs (VERSION_OPTION_DESCRIPTION, stdout);
133 fputs (_("\
135 N may have a multiplier suffix:\n\
136 b 512, kB 1000, K 1024, MB 1000*1000, M 1024*1024,\n\
137 GB 1000*1000*1000, G 1024*1024*1024, and so on for T, P, E, Z, Y.\n\
138 "), stdout);
139 emit_bug_reporting_address ();
141 exit (status);
144 static void
145 diagnose_copy_fd_failure (enum Copy_fd_status err, char const *filename)
147 switch (err)
149 case COPY_FD_READ_ERROR:
150 error (0, errno, _("error reading %s"), quote (filename));
151 break;
152 case COPY_FD_WRITE_ERROR:
153 error (0, errno, _("error writing %s"), quote (filename));
154 break;
155 case COPY_FD_UNEXPECTED_EOF:
156 error (0, errno, _("%s: file has shrunk too much"), quote (filename));
157 break;
158 default:
159 abort ();
163 static void
164 write_header (const char *filename)
166 static bool first_file = true;
168 printf ("%s==> %s <==\n", (first_file ? "" : "\n"), filename);
169 first_file = false;
172 /* Copy no more than N_BYTES from file descriptor SRC_FD to O_STREAM.
173 Return an appropriate indication of success or failure. */
175 static enum Copy_fd_status
176 copy_fd (int src_fd, FILE *o_stream, uintmax_t n_bytes)
178 char buf[BUFSIZ];
179 const size_t buf_size = sizeof (buf);
181 /* Copy the file contents. */
182 while (0 < n_bytes)
184 size_t n_to_read = MIN (buf_size, n_bytes);
185 size_t n_read = safe_read (src_fd, buf, n_to_read);
186 if (n_read == SAFE_READ_ERROR)
187 return COPY_FD_READ_ERROR;
189 n_bytes -= n_read;
191 if (n_read == 0 && n_bytes != 0)
192 return COPY_FD_UNEXPECTED_EOF;
194 if (fwrite (buf, 1, n_read, o_stream) < n_read)
195 return COPY_FD_WRITE_ERROR;
198 return COPY_FD_OK;
201 /* Print all but the last N_ELIDE lines from the input available via
202 the non-seekable file descriptor FD. Return true upon success.
203 Give a diagnostic and return false upon error. */
204 static bool
205 elide_tail_bytes_pipe (const char *filename, int fd, uintmax_t n_elide_0)
207 size_t n_elide = n_elide_0;
209 #ifndef HEAD_TAIL_PIPE_READ_BUFSIZE
210 # define HEAD_TAIL_PIPE_READ_BUFSIZE BUFSIZ
211 #endif
212 #define READ_BUFSIZE HEAD_TAIL_PIPE_READ_BUFSIZE
214 /* If we're eliding no more than this many bytes, then it's ok to allocate
215 more memory in order to use a more time-efficient algorithm.
216 FIXME: use a fraction of available memory instead, as in sort.
217 FIXME: is this even worthwhile? */
218 #ifndef HEAD_TAIL_PIPE_BYTECOUNT_THRESHOLD
219 # define HEAD_TAIL_PIPE_BYTECOUNT_THRESHOLD 1024 * 1024
220 #endif
222 #if HEAD_TAIL_PIPE_BYTECOUNT_THRESHOLD < 2 * READ_BUFSIZE
223 "HEAD_TAIL_PIPE_BYTECOUNT_THRESHOLD must be at least 2 * READ_BUFSIZE"
224 #endif
226 if (SIZE_MAX < n_elide_0 + READ_BUFSIZE)
228 char umax_buf[INT_BUFSIZE_BOUND (uintmax_t)];
229 error (EXIT_FAILURE, 0, _("%s: number of bytes is too large"),
230 umaxtostr (n_elide_0, umax_buf));
233 /* Two cases to consider...
234 1) n_elide is small enough that we can afford to double-buffer:
235 allocate 2 * (READ_BUFSIZE + n_elide) bytes
236 2) n_elide is too big for that, so we allocate only
237 (READ_BUFSIZE + n_elide) bytes
239 FIXME: profile, to see if double-buffering is worthwhile
241 CAUTION: do not fail (out of memory) when asked to elide
242 a ridiculous amount, but when given only a small input. */
244 if (n_elide <= HEAD_TAIL_PIPE_BYTECOUNT_THRESHOLD)
246 bool ok = true;
247 bool first = true;
248 bool eof = false;
249 size_t n_to_read = READ_BUFSIZE + n_elide;
250 bool i;
251 char *b[2];
252 b[0] = xnmalloc (2, n_to_read);
253 b[1] = b[0] + n_to_read;
255 for (i = false; ! eof ; i = !i)
257 size_t n_read = full_read (fd, b[i], n_to_read);
258 size_t delta = 0;
259 if (n_read < n_to_read)
261 if (errno != 0)
263 error (0, errno, _("error reading %s"), quote (filename));
264 ok = false;
265 break;
268 /* reached EOF */
269 if (n_read <= n_elide)
271 if (first)
273 /* The input is no larger than the number of bytes
274 to elide. So there's nothing to output, and
275 we're done. */
277 else
279 delta = n_elide - n_read;
282 eof = true;
285 /* Output any (but maybe just part of the) elided data from
286 the previous round. */
287 if ( ! first)
289 /* Don't bother checking for errors here.
290 If there's a failure, the test of the following
291 fwrite or in close_stdout will catch it. */
292 fwrite (b[!i] + READ_BUFSIZE, 1, n_elide - delta, stdout);
294 first = false;
296 if (n_elide < n_read
297 && fwrite (b[i], 1, n_read - n_elide, stdout) < n_read - n_elide)
299 error (0, errno, _("write error"));
300 ok = false;
301 break;
305 free (b[0]);
306 return ok;
308 else
310 /* Read blocks of size READ_BUFSIZE, until we've read at least n_elide
311 bytes. Then, for each new buffer we read, also write an old one. */
313 bool ok = true;
314 bool eof = false;
315 size_t n_read;
316 bool buffered_enough;
317 size_t i, i_next;
318 char **b;
319 /* Round n_elide up to a multiple of READ_BUFSIZE. */
320 size_t rem = READ_BUFSIZE - (n_elide % READ_BUFSIZE);
321 size_t n_elide_round = n_elide + rem;
322 size_t n_bufs = n_elide_round / READ_BUFSIZE + 1;
323 b = xcalloc (n_bufs, sizeof *b);
325 buffered_enough = false;
326 for (i = 0, i_next = 1; !eof; i = i_next, i_next = (i_next + 1) % n_bufs)
328 if (b[i] == NULL)
329 b[i] = xmalloc (READ_BUFSIZE);
330 n_read = full_read (fd, b[i], READ_BUFSIZE);
331 if (n_read < READ_BUFSIZE)
333 if (errno != 0)
335 error (0, errno, _("error reading %s"), quote (filename));
336 ok = false;
337 goto free_mem;
339 eof = true;
342 if (i + 1 == n_bufs)
343 buffered_enough = true;
345 if (buffered_enough)
347 if (fwrite (b[i_next], 1, n_read, stdout) < n_read)
349 error (0, errno, _("write error"));
350 ok = false;
351 goto free_mem;
356 /* Output any remainder: rem bytes from b[i] + n_read. */
357 if (rem)
359 if (buffered_enough)
361 size_t n_bytes_left_in_b_i = READ_BUFSIZE - n_read;
362 if (rem < n_bytes_left_in_b_i)
364 fwrite (b[i] + n_read, 1, rem, stdout);
366 else
368 fwrite (b[i] + n_read, 1, n_bytes_left_in_b_i, stdout);
369 fwrite (b[i_next], 1, rem - n_bytes_left_in_b_i, stdout);
372 else if (i + 1 == n_bufs)
374 /* This happens when n_elide < file_size < n_elide_round.
376 |READ_BUF.|
377 | | rem |
378 |---------!---------!---------!---------|
379 |---- n_elide ---------|
380 | | x |
381 | |y |
382 |---- file size -----------|
383 | |n_read|
384 |---- n_elide_round ----------|
386 size_t y = READ_BUFSIZE - rem;
387 size_t x = n_read - y;
388 fwrite (b[i_next], 1, x, stdout);
392 free_mem:;
393 for (i = 0; i < n_bufs; i++)
394 free (b[i]);
395 free (b);
397 return ok;
401 /* Print all but the last N_ELIDE lines from the input available
402 via file descriptor FD. Return true upon success.
403 Give a diagnostic and return false upon error. */
405 /* NOTE: if the input file shrinks by more than N_ELIDE bytes between
406 the length determination and the actual reading, then head fails. */
408 static bool
409 elide_tail_bytes_file (const char *filename, int fd, uintmax_t n_elide)
411 struct stat stats;
413 if (presume_input_pipe || fstat (fd, &stats) || ! S_ISREG (stats.st_mode))
415 return elide_tail_bytes_pipe (filename, fd, n_elide);
417 else
419 off_t current_pos, end_pos;
420 uintmax_t bytes_remaining;
421 off_t diff;
422 enum Copy_fd_status err;
424 if ((current_pos = lseek (fd, (off_t) 0, SEEK_CUR)) == -1
425 || (end_pos = lseek (fd, (off_t) 0, SEEK_END)) == -1)
427 error (0, errno, _("cannot lseek %s"), quote (filename));
428 return false;
431 /* Be careful here. The current position may actually be
432 beyond the end of the file. */
433 bytes_remaining = (diff = end_pos - current_pos) < 0 ? 0 : diff;
435 if (bytes_remaining <= n_elide)
436 return true;
438 /* Seek back to `current' position, then copy the required
439 number of bytes from fd. */
440 if (lseek (fd, (off_t) 0, current_pos) == -1)
442 error (0, errno, _("%s: cannot lseek back to original position"),
443 quote (filename));
444 return false;
447 err = copy_fd (fd, stdout, bytes_remaining - n_elide);
448 if (err == COPY_FD_OK)
449 return true;
451 diagnose_copy_fd_failure (err, filename);
452 return false;
456 /* Print all but the last N_ELIDE lines from the input stream
457 open for reading via file descriptor FD.
458 Buffer the specified number of lines as a linked list of LBUFFERs,
459 adding them as needed. Return true if successful. */
461 static bool
462 elide_tail_lines_pipe (const char *filename, int fd, uintmax_t n_elide)
464 struct linebuffer
466 char buffer[BUFSIZ];
467 size_t nbytes;
468 size_t nlines;
469 struct linebuffer *next;
471 typedef struct linebuffer LBUFFER;
472 LBUFFER *first, *last, *tmp;
473 size_t total_lines = 0; /* Total number of newlines in all buffers. */
474 bool ok = true;
475 size_t n_read; /* Size in bytes of most recent read */
477 first = last = xmalloc (sizeof (LBUFFER));
478 first->nbytes = first->nlines = 0;
479 first->next = NULL;
480 tmp = xmalloc (sizeof (LBUFFER));
482 /* Always read into a fresh buffer.
483 Read, (producing no output) until we've accumulated at least
484 n_elide newlines, or until EOF, whichever comes first. */
485 while (1)
487 n_read = safe_read (fd, tmp->buffer, BUFSIZ);
488 if (n_read == 0 || n_read == SAFE_READ_ERROR)
489 break;
490 tmp->nbytes = n_read;
491 tmp->nlines = 0;
492 tmp->next = NULL;
494 /* Count the number of newlines just read. */
496 char const *buffer_end = tmp->buffer + n_read;
497 char const *p = tmp->buffer;
498 while ((p = memchr (p, '\n', buffer_end - p)))
500 ++p;
501 ++tmp->nlines;
504 total_lines += tmp->nlines;
506 /* If there is enough room in the last buffer read, just append the new
507 one to it. This is because when reading from a pipe, `n_read' can
508 often be very small. */
509 if (tmp->nbytes + last->nbytes < BUFSIZ)
511 memcpy (&last->buffer[last->nbytes], tmp->buffer, tmp->nbytes);
512 last->nbytes += tmp->nbytes;
513 last->nlines += tmp->nlines;
515 else
517 /* If there's not enough room, link the new buffer onto the end of
518 the list, then either free up the oldest buffer for the next
519 read if that would leave enough lines, or else malloc a new one.
520 Some compaction mechanism is possible but probably not
521 worthwhile. */
522 last = last->next = tmp;
523 if (n_elide < total_lines - first->nlines)
525 fwrite (first->buffer, 1, first->nbytes, stdout);
526 tmp = first;
527 total_lines -= first->nlines;
528 first = first->next;
530 else
531 tmp = xmalloc (sizeof (LBUFFER));
535 free (tmp);
537 if (n_read == SAFE_READ_ERROR)
539 error (0, errno, _("error reading %s"), quote (filename));
540 ok = false;
541 goto free_lbuffers;
544 /* If we read any bytes at all, count the incomplete line
545 on files that don't end with a newline. */
546 if (last->nbytes && last->buffer[last->nbytes - 1] != '\n')
548 ++last->nlines;
549 ++total_lines;
552 for (tmp = first; n_elide < total_lines - tmp->nlines; tmp = tmp->next)
554 fwrite (tmp->buffer, 1, tmp->nbytes, stdout);
555 total_lines -= tmp->nlines;
558 /* Print the first `total_lines - n_elide' lines of tmp->buffer. */
559 if (n_elide < total_lines)
561 size_t n = total_lines - n_elide;
562 char const *buffer_end = tmp->buffer + tmp->nbytes;
563 char const *p = tmp->buffer;
564 while (n && (p = memchr (p, '\n', buffer_end - p)))
566 ++p;
567 ++tmp->nlines;
568 --n;
570 fwrite (tmp->buffer, 1, p - tmp->buffer, stdout);
573 free_lbuffers:
574 while (first)
576 tmp = first->next;
577 free (first);
578 first = tmp;
580 return ok;
583 /* Output all but the last N_LINES lines of the input stream defined by
584 FD, START_POS, and END_POS.
585 START_POS is the starting position of the read pointer for the file
586 associated with FD (may be nonzero).
587 END_POS is the file offset of EOF (one larger than offset of last byte).
588 Return true upon success.
589 Give a diagnostic and return false upon error.
591 NOTE: this code is very similar to that of tail.c's file_lines function.
592 Unfortunately, factoring out some common core looks like it'd result
593 in a less efficient implementation or a messy interface. */
594 static bool
595 elide_tail_lines_seekable (const char *pretty_filename, int fd,
596 uintmax_t n_lines,
597 off_t start_pos, off_t end_pos)
599 char buffer[BUFSIZ];
600 size_t bytes_read;
601 off_t pos = end_pos;
603 /* Set `bytes_read' to the size of the last, probably partial, buffer;
604 0 < `bytes_read' <= `BUFSIZ'. */
605 bytes_read = (pos - start_pos) % BUFSIZ;
606 if (bytes_read == 0)
607 bytes_read = BUFSIZ;
608 /* Make `pos' a multiple of `BUFSIZ' (0 if the file is short), so that all
609 reads will be on block boundaries, which might increase efficiency. */
610 pos -= bytes_read;
611 if (lseek (fd, pos, SEEK_SET) < 0)
613 char offset_buf[INT_BUFSIZE_BOUND (off_t)];
614 error (0, errno, _("%s: cannot seek to offset %s"),
615 pretty_filename, offtostr (pos, offset_buf));
616 return false;
618 bytes_read = safe_read (fd, buffer, bytes_read);
619 if (bytes_read == SAFE_READ_ERROR)
621 error (0, errno, _("error reading %s"), quote (pretty_filename));
622 return false;
625 /* Count the incomplete line on files that don't end with a newline. */
626 if (bytes_read && buffer[bytes_read - 1] != '\n')
627 --n_lines;
629 while (1)
631 /* Scan backward, counting the newlines in this bufferfull. */
633 size_t n = bytes_read;
634 while (n)
636 char const *nl;
637 nl = memrchr (buffer, '\n', n);
638 if (nl == NULL)
639 break;
640 n = nl - buffer;
641 if (n_lines-- == 0)
643 /* Found it. */
644 /* If necessary, restore the file pointer and copy
645 input to output up to position, POS. */
646 if (start_pos < pos)
648 enum Copy_fd_status err;
649 if (lseek (fd, start_pos, SEEK_SET) < 0)
651 /* Failed to reposition file pointer. */
652 error (0, errno,
653 "%s: unable to restore file pointer to initial offset",
654 quote (pretty_filename));
655 return false;
658 err = copy_fd (fd, stdout, pos - start_pos);
659 if (err != COPY_FD_OK)
661 diagnose_copy_fd_failure (err, pretty_filename);
662 return false;
666 /* Output the initial portion of the buffer
667 in which we found the desired newline byte.
668 Don't bother testing for failure for such a small amount.
669 Any failure will be detected upon close. */
670 fwrite (buffer, 1, n + 1, stdout);
671 return true;
675 /* Not enough newlines in that bufferfull. */
676 if (pos == start_pos)
678 /* Not enough lines in the file. */
679 return true;
681 pos -= BUFSIZ;
682 if (lseek (fd, pos, SEEK_SET) < 0)
684 char offset_buf[INT_BUFSIZE_BOUND (off_t)];
685 error (0, errno, _("%s: cannot seek to offset %s"),
686 pretty_filename, offtostr (pos, offset_buf));
687 return false;
690 bytes_read = safe_read (fd, buffer, BUFSIZ);
691 if (bytes_read == SAFE_READ_ERROR)
693 error (0, errno, _("error reading %s"), quote (pretty_filename));
694 return false;
697 /* FIXME: is this dead code?
698 Consider the test, pos == start_pos, above. */
699 if (bytes_read == 0)
700 return true;
704 /* Print all but the last N_ELIDE lines from the input available
705 via file descriptor FD. Return true upon success.
706 Give a diagnostic and return nonzero upon error. */
708 static bool
709 elide_tail_lines_file (const char *filename, int fd, uintmax_t n_elide)
711 if (!presume_input_pipe)
713 /* Find the offset, OFF, of the Nth newline from the end,
714 but not counting the last byte of the file.
715 If found, write from current position to OFF, inclusive.
716 Otherwise, just return true. */
718 off_t start_pos = lseek (fd, (off_t) 0, SEEK_CUR);
719 off_t end_pos = lseek (fd, (off_t) 0, SEEK_END);
720 if (0 <= start_pos && start_pos < end_pos)
722 /* If the file is empty, we're done. */
723 if (end_pos == 0)
724 return true;
726 return elide_tail_lines_seekable (filename, fd, n_elide,
727 start_pos, end_pos);
730 /* lseek failed or the end offset precedes start.
731 Fall through. */
734 return elide_tail_lines_pipe (filename, fd, n_elide);
737 static bool
738 head_bytes (const char *filename, int fd, uintmax_t bytes_to_write)
740 char buffer[BUFSIZ];
741 size_t bytes_to_read = BUFSIZ;
743 while (bytes_to_write)
745 size_t bytes_read;
746 if (bytes_to_write < bytes_to_read)
747 bytes_to_read = bytes_to_write;
748 bytes_read = safe_read (fd, buffer, bytes_to_read);
749 if (bytes_read == SAFE_READ_ERROR)
751 error (0, errno, _("error reading %s"), quote (filename));
752 return false;
754 if (bytes_read == 0)
755 break;
756 if (fwrite (buffer, 1, bytes_read, stdout) < bytes_read)
757 error (EXIT_FAILURE, errno, _("write error"));
758 bytes_to_write -= bytes_read;
760 return true;
763 static bool
764 head_lines (const char *filename, int fd, uintmax_t lines_to_write)
766 char buffer[BUFSIZ];
768 while (lines_to_write)
770 size_t bytes_read = safe_read (fd, buffer, BUFSIZ);
771 size_t bytes_to_write = 0;
773 if (bytes_read == SAFE_READ_ERROR)
775 error (0, errno, _("error reading %s"), quote (filename));
776 return false;
778 if (bytes_read == 0)
779 break;
780 while (bytes_to_write < bytes_read)
781 if (buffer[bytes_to_write++] == '\n' && --lines_to_write == 0)
783 off_t n_bytes_past_EOL = bytes_read - bytes_to_write;
784 /* If we have read more data than that on the specified number
785 of lines, try to seek back to the position we would have
786 gotten to had we been reading one byte at a time. */
787 if (lseek (fd, -n_bytes_past_EOL, SEEK_CUR) < 0)
789 int e = errno;
790 struct stat st;
791 if (fstat (fd, &st) != 0 || S_ISREG (st.st_mode))
792 error (0, e, _("cannot reposition file pointer for %s"),
793 quote (filename));
795 break;
797 if (fwrite (buffer, 1, bytes_to_write, stdout) < bytes_to_write)
798 error (EXIT_FAILURE, errno, _("write error"));
800 return true;
803 static bool
804 head (const char *filename, int fd, uintmax_t n_units, bool count_lines,
805 bool elide_from_end)
807 if (print_headers)
808 write_header (filename);
810 if (elide_from_end)
812 if (count_lines)
814 return elide_tail_lines_file (filename, fd, n_units);
816 else
818 return elide_tail_bytes_file (filename, fd, n_units);
821 if (count_lines)
822 return head_lines (filename, fd, n_units);
823 else
824 return head_bytes (filename, fd, n_units);
827 static bool
828 head_file (const char *filename, uintmax_t n_units, bool count_lines,
829 bool elide_from_end)
831 int fd;
832 bool ok;
833 bool is_stdin = STREQ (filename, "-");
835 if (is_stdin)
837 have_read_stdin = true;
838 fd = STDIN_FILENO;
839 filename = _("standard input");
840 if (O_BINARY && ! isatty (STDIN_FILENO))
841 freopen (NULL, "rb", stdin);
843 else
845 fd = open (filename, O_RDONLY | O_BINARY);
846 if (fd < 0)
848 error (0, errno, _("cannot open %s for reading"), quote (filename));
849 return false;
853 ok = head (filename, fd, n_units, count_lines, elide_from_end);
854 if (!is_stdin && close (fd) != 0)
856 error (0, errno, _("closing %s"), quote (filename));
857 return false;
859 return ok;
862 /* Convert a string of decimal digits, N_STRING, with an optional suffinx
863 to an integral value. Upon successful conversion,
864 return that value. If it cannot be converted, give a diagnostic and exit.
865 COUNT_LINES indicates whether N_STRING is a number of bytes or a number
866 of lines. It is used solely to give a more specific diagnostic. */
868 static uintmax_t
869 string_to_integer (bool count_lines, const char *n_string)
871 strtol_error s_err;
872 uintmax_t n;
874 s_err = xstrtoumax (n_string, NULL, 10, &n, "bkKmMGTPEZY0");
876 if (s_err == LONGINT_OVERFLOW)
878 error (EXIT_FAILURE, 0,
879 _("%s: %s is so large that it is not representable"), n_string,
880 count_lines ? _("number of lines") : _("number of bytes"));
883 if (s_err != LONGINT_OK)
885 error (EXIT_FAILURE, 0, "%s: %s", n_string,
886 (count_lines
887 ? _("invalid number of lines")
888 : _("invalid number of bytes")));
891 return n;
895 main (int argc, char **argv)
897 enum header_mode header_mode = multiple_files;
898 bool ok = true;
899 int c;
900 size_t i;
902 /* Number of items to print. */
903 uintmax_t n_units = DEFAULT_NUMBER;
905 /* If true, interpret the numeric argument as the number of lines.
906 Otherwise, interpret it as the number of bytes. */
907 bool count_lines = true;
909 /* Elide the specified number of lines or bytes, counting from
910 the end of the file. */
911 bool elide_from_end = false;
913 /* Initializer for file_list if no file-arguments
914 were specified on the command line. */
915 static char const *const default_file_list[] = {"-", NULL};
916 char const *const *file_list;
918 initialize_main (&argc, &argv);
919 set_program_name (argv[0]);
920 setlocale (LC_ALL, "");
921 bindtextdomain (PACKAGE, LOCALEDIR);
922 textdomain (PACKAGE);
924 atexit (close_stdout);
926 have_read_stdin = false;
928 print_headers = false;
930 if (1 < argc && argv[1][0] == '-' && ISDIGIT (argv[1][1]))
932 char *a = argv[1];
933 char *n_string = ++a;
934 char *end_n_string;
935 char multiplier_char = 0;
937 /* Old option syntax; a dash, one or more digits, and one or
938 more option letters. Move past the number. */
939 do ++a;
940 while (ISDIGIT (*a));
942 /* Pointer to the byte after the last digit. */
943 end_n_string = a;
945 /* Parse any appended option letters. */
946 for (; *a; a++)
948 switch (*a)
950 case 'c':
951 count_lines = false;
952 multiplier_char = 0;
953 break;
955 case 'b':
956 case 'k':
957 case 'm':
958 count_lines = false;
959 multiplier_char = *a;
960 break;
962 case 'l':
963 count_lines = true;
964 break;
966 case 'q':
967 header_mode = never;
968 break;
970 case 'v':
971 header_mode = always;
972 break;
974 default:
975 error (0, 0, _("invalid trailing option -- %c"), *a);
976 usage (EXIT_FAILURE);
980 /* Append the multiplier character (if any) onto the end of
981 the digit string. Then add NUL byte if necessary. */
982 *end_n_string = multiplier_char;
983 if (multiplier_char)
984 *(++end_n_string) = 0;
986 n_units = string_to_integer (count_lines, n_string);
988 /* Make the options we just parsed invisible to getopt. */
989 argv[1] = argv[0];
990 argv++;
991 argc--;
994 while ((c = getopt_long (argc, argv, "c:n:qv0123456789", long_options, NULL))
995 != -1)
997 switch (c)
999 case PRESUME_INPUT_PIPE_OPTION:
1000 presume_input_pipe = true;
1001 break;
1003 case 'c':
1004 count_lines = false;
1005 elide_from_end = (*optarg == '-');
1006 if (elide_from_end)
1007 ++optarg;
1008 n_units = string_to_integer (count_lines, optarg);
1009 break;
1011 case 'n':
1012 count_lines = true;
1013 elide_from_end = (*optarg == '-');
1014 if (elide_from_end)
1015 ++optarg;
1016 n_units = string_to_integer (count_lines, optarg);
1017 break;
1019 case 'q':
1020 header_mode = never;
1021 break;
1023 case 'v':
1024 header_mode = always;
1025 break;
1027 case_GETOPT_HELP_CHAR;
1029 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
1031 default:
1032 if (ISDIGIT (c))
1033 error (0, 0, _("invalid trailing option -- %c"), c);
1034 usage (EXIT_FAILURE);
1038 if (header_mode == always
1039 || (header_mode == multiple_files && optind < argc - 1))
1040 print_headers = true;
1042 if ( ! count_lines && elide_from_end && OFF_T_MAX < n_units)
1044 char umax_buf[INT_BUFSIZE_BOUND (uintmax_t)];
1045 error (EXIT_FAILURE, 0, _("%s: number of bytes is too large"),
1046 umaxtostr (n_units, umax_buf));
1049 file_list = (optind < argc
1050 ? (char const *const *) &argv[optind]
1051 : default_file_list);
1053 if (O_BINARY && ! isatty (STDOUT_FILENO))
1054 freopen (NULL, "wb", stdout);
1056 for (i = 0; file_list[i]; ++i)
1057 ok &= head_file (file_list[i], n_units, count_lines, elide_from_end);
1059 if (have_read_stdin && close (STDIN_FILENO) < 0)
1060 error (EXIT_FAILURE, errno, "-");
1062 exit (ok ? EXIT_SUCCESS : EXIT_FAILURE);