doc: with cp -n, option -f is not redundant but ignored
[coreutils.git] / src / head.c
blobc13c064c470a1f97ee0fd0df2f2877f0527fe4a8
1 /* head -- output first part of file(s)
2 Copyright (C) 1989-2012 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-read.h"
36 #include "quote.h"
37 #include "safe-read.h"
38 #include "xfreopen.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 emit_try_help ();
103 else
105 printf (_("\
106 Usage: %s [OPTION]... [FILE]...\n\
108 program_name);
109 fputs (_("\
110 Print the first 10 lines of each FILE to standard output.\n\
111 With more than one FILE, precede each with a header giving the file name.\n\
112 With no FILE, or when FILE is -, read standard input.\n\
114 "), stdout);
115 fputs (_("\
116 Mandatory arguments to long options are mandatory for short options too.\n\
117 "), stdout);
118 fputs (_("\
119 -c, --bytes=[-]K print the first K bytes of each file;\n\
120 with the leading '-', print all but the last\n\
121 K bytes of each file\n\
122 -n, --lines=[-]K print the first K lines instead of the first 10;\n\
123 with the leading '-', print all but the last\n\
124 K lines of each file\n\
125 "), stdout);
126 fputs (_("\
127 -q, --quiet, --silent never print headers giving file names\n\
128 -v, --verbose always print headers giving file names\n\
129 "), stdout);
130 fputs (HELP_OPTION_DESCRIPTION, stdout);
131 fputs (VERSION_OPTION_DESCRIPTION, stdout);
132 fputs (_("\
134 K may have a multiplier suffix:\n\
135 b 512, kB 1000, K 1024, MB 1000*1000, M 1024*1024,\n\
136 GB 1000*1000*1000, G 1024*1024*1024, and so on for T, P, E, Z, Y.\n\
137 "), stdout);
138 emit_ancillary_info ();
140 exit (status);
143 static void
144 diagnose_copy_fd_failure (enum Copy_fd_status err, char const *filename)
146 switch (err)
148 case COPY_FD_READ_ERROR:
149 error (0, errno, _("error reading %s"), quote (filename));
150 break;
151 case COPY_FD_WRITE_ERROR:
152 error (0, errno, _("error writing %s"), quote (filename));
153 break;
154 case COPY_FD_UNEXPECTED_EOF:
155 error (0, errno, _("%s: file has shrunk too much"), quote (filename));
156 break;
157 default:
158 abort ();
162 static void
163 write_header (const char *filename)
165 static bool first_file = true;
167 printf ("%s==> %s <==\n", (first_file ? "" : "\n"), filename);
168 first_file = false;
171 /* Copy no more than N_BYTES from file descriptor SRC_FD to O_STREAM.
172 Return an appropriate indication of success or failure. */
174 static enum Copy_fd_status
175 copy_fd (int src_fd, FILE *o_stream, uintmax_t n_bytes)
177 char buf[BUFSIZ];
178 const size_t buf_size = sizeof (buf);
180 /* Copy the file contents. */
181 while (0 < n_bytes)
183 size_t n_to_read = MIN (buf_size, n_bytes);
184 size_t n_read = safe_read (src_fd, buf, n_to_read);
185 if (n_read == SAFE_READ_ERROR)
186 return COPY_FD_READ_ERROR;
188 n_bytes -= n_read;
190 if (n_read == 0 && n_bytes != 0)
191 return COPY_FD_UNEXPECTED_EOF;
193 if (fwrite (buf, 1, n_read, o_stream) < n_read)
194 return COPY_FD_WRITE_ERROR;
197 return COPY_FD_OK;
200 /* Print all but the last N_ELIDE lines from the input available via
201 the non-seekable file descriptor FD. Return true upon success.
202 Give a diagnostic and return false upon error. */
203 static bool
204 elide_tail_bytes_pipe (const char *filename, int fd, uintmax_t n_elide_0)
206 size_t n_elide = n_elide_0;
208 #ifndef HEAD_TAIL_PIPE_READ_BUFSIZE
209 # define HEAD_TAIL_PIPE_READ_BUFSIZE BUFSIZ
210 #endif
211 #define READ_BUFSIZE HEAD_TAIL_PIPE_READ_BUFSIZE
213 /* If we're eliding no more than this many bytes, then it's ok to allocate
214 more memory in order to use a more time-efficient algorithm.
215 FIXME: use a fraction of available memory instead, as in sort.
216 FIXME: is this even worthwhile? */
217 #ifndef HEAD_TAIL_PIPE_BYTECOUNT_THRESHOLD
218 # define HEAD_TAIL_PIPE_BYTECOUNT_THRESHOLD 1024 * 1024
219 #endif
221 #if HEAD_TAIL_PIPE_BYTECOUNT_THRESHOLD < 2 * READ_BUFSIZE
222 "HEAD_TAIL_PIPE_BYTECOUNT_THRESHOLD must be at least 2 * READ_BUFSIZE"
223 #endif
225 if (SIZE_MAX < n_elide_0 + READ_BUFSIZE)
227 char umax_buf[INT_BUFSIZE_BOUND (n_elide_0)];
228 error (EXIT_FAILURE, 0, _("%s: number of bytes is too large"),
229 umaxtostr (n_elide_0, umax_buf));
232 /* Two cases to consider...
233 1) n_elide is small enough that we can afford to double-buffer:
234 allocate 2 * (READ_BUFSIZE + n_elide) bytes
235 2) n_elide is too big for that, so we allocate only
236 (READ_BUFSIZE + n_elide) bytes
238 FIXME: profile, to see if double-buffering is worthwhile
240 CAUTION: do not fail (out of memory) when asked to elide
241 a ridiculous amount, but when given only a small input. */
243 if (n_elide <= HEAD_TAIL_PIPE_BYTECOUNT_THRESHOLD)
245 bool ok = true;
246 bool first = true;
247 bool eof = false;
248 size_t n_to_read = READ_BUFSIZE + n_elide;
249 bool i;
250 char *b[2];
251 b[0] = xnmalloc (2, n_to_read);
252 b[1] = b[0] + n_to_read;
254 for (i = false; ! eof ; i = !i)
256 size_t n_read = full_read (fd, b[i], n_to_read);
257 size_t delta = 0;
258 if (n_read < n_to_read)
260 if (errno != 0)
262 error (0, errno, _("error reading %s"), quote (filename));
263 ok = false;
264 break;
267 /* reached EOF */
268 if (n_read <= n_elide)
270 if (first)
272 /* The input is no larger than the number of bytes
273 to elide. So there's nothing to output, and
274 we're done. */
276 else
278 delta = n_elide - n_read;
281 eof = true;
284 /* Output any (but maybe just part of the) elided data from
285 the previous round. */
286 if ( ! first)
288 /* Don't bother checking for errors here.
289 If there's a failure, the test of the following
290 fwrite or in close_stdout will catch it. */
291 fwrite (b[!i] + READ_BUFSIZE, 1, n_elide - delta, stdout);
293 first = false;
295 if (n_elide < n_read
296 && fwrite (b[i], 1, n_read - n_elide, stdout) < n_read - n_elide)
298 error (0, errno, _("write error"));
299 ok = false;
300 break;
304 free (b[0]);
305 return ok;
307 else
309 /* Read blocks of size READ_BUFSIZE, until we've read at least n_elide
310 bytes. Then, for each new buffer we read, also write an old one. */
312 bool ok = true;
313 bool eof = false;
314 size_t n_read;
315 bool buffered_enough;
316 size_t i, i_next;
317 char **b;
318 /* Round n_elide up to a multiple of READ_BUFSIZE. */
319 size_t rem = READ_BUFSIZE - (n_elide % READ_BUFSIZE);
320 size_t n_elide_round = n_elide + rem;
321 size_t n_bufs = n_elide_round / READ_BUFSIZE + 1;
322 b = xcalloc (n_bufs, sizeof *b);
324 buffered_enough = false;
325 for (i = 0, i_next = 1; !eof; i = i_next, i_next = (i_next + 1) % n_bufs)
327 if (b[i] == NULL)
328 b[i] = xmalloc (READ_BUFSIZE);
329 n_read = full_read (fd, b[i], READ_BUFSIZE);
330 if (n_read < READ_BUFSIZE)
332 if (errno != 0)
334 error (0, errno, _("error reading %s"), quote (filename));
335 ok = false;
336 goto free_mem;
338 eof = true;
341 if (i + 1 == n_bufs)
342 buffered_enough = true;
344 if (buffered_enough)
346 if (fwrite (b[i_next], 1, n_read, stdout) < n_read)
348 error (0, errno, _("write error"));
349 ok = false;
350 goto free_mem;
355 /* Output any remainder: rem bytes from b[i] + n_read. */
356 if (rem)
358 if (buffered_enough)
360 size_t n_bytes_left_in_b_i = READ_BUFSIZE - n_read;
361 if (rem < n_bytes_left_in_b_i)
363 fwrite (b[i] + n_read, 1, rem, stdout);
365 else
367 fwrite (b[i] + n_read, 1, n_bytes_left_in_b_i, stdout);
368 fwrite (b[i_next], 1, rem - n_bytes_left_in_b_i, stdout);
371 else if (i + 1 == n_bufs)
373 /* This happens when n_elide < file_size < n_elide_round.
375 |READ_BUF.|
376 | | rem |
377 |---------!---------!---------!---------|
378 |---- n_elide ---------|
379 | | x |
380 | |y |
381 |---- file size -----------|
382 | |n_read|
383 |---- n_elide_round ----------|
385 size_t y = READ_BUFSIZE - rem;
386 size_t x = n_read - y;
387 fwrite (b[i_next], 1, x, stdout);
391 free_mem:
392 for (i = 0; i < n_bufs; i++)
393 free (b[i]);
394 free (b);
396 return ok;
400 /* Print all but the last N_ELIDE lines from the input available
401 via file descriptor FD. Return true upon success.
402 Give a diagnostic and return false upon error. */
404 /* NOTE: if the input file shrinks by more than N_ELIDE bytes between
405 the length determination and the actual reading, then head fails. */
407 static bool
408 elide_tail_bytes_file (const char *filename, int fd, uintmax_t n_elide)
410 struct stat stats;
412 if (presume_input_pipe || fstat (fd, &stats) || ! S_ISREG (stats.st_mode))
414 return elide_tail_bytes_pipe (filename, fd, n_elide);
416 else
418 off_t current_pos, end_pos;
419 uintmax_t bytes_remaining;
420 off_t diff;
421 enum Copy_fd_status err;
423 if ((current_pos = lseek (fd, 0, SEEK_CUR)) == -1
424 || (end_pos = lseek (fd, 0, SEEK_END)) == -1)
426 error (0, errno, _("cannot lseek %s"), quote (filename));
427 return false;
430 /* Be careful here. The current position may actually be
431 beyond the end of the file. */
432 bytes_remaining = (diff = end_pos - current_pos) < 0 ? 0 : diff;
434 if (bytes_remaining <= n_elide)
435 return true;
437 /* Seek back to 'current' position, then copy the required
438 number of bytes from fd. */
439 if (lseek (fd, 0, current_pos) == -1)
441 error (0, errno, _("%s: cannot lseek back to original position"),
442 quote (filename));
443 return false;
446 err = copy_fd (fd, stdout, bytes_remaining - n_elide);
447 if (err == COPY_FD_OK)
448 return true;
450 diagnose_copy_fd_failure (err, filename);
451 return false;
455 /* Print all but the last N_ELIDE lines from the input stream
456 open for reading via file descriptor FD.
457 Buffer the specified number of lines as a linked list of LBUFFERs,
458 adding them as needed. Return true if successful. */
460 static bool
461 elide_tail_lines_pipe (const char *filename, int fd, uintmax_t n_elide)
463 struct linebuffer
465 char buffer[BUFSIZ];
466 size_t nbytes;
467 size_t nlines;
468 struct linebuffer *next;
470 typedef struct linebuffer LBUFFER;
471 LBUFFER *first, *last, *tmp;
472 size_t total_lines = 0; /* Total number of newlines in all buffers. */
473 bool ok = true;
474 size_t n_read; /* Size in bytes of most recent read */
476 first = last = xmalloc (sizeof (LBUFFER));
477 first->nbytes = first->nlines = 0;
478 first->next = NULL;
479 tmp = xmalloc (sizeof (LBUFFER));
481 /* Always read into a fresh buffer.
482 Read, (producing no output) until we've accumulated at least
483 n_elide newlines, or until EOF, whichever comes first. */
484 while (1)
486 n_read = safe_read (fd, tmp->buffer, BUFSIZ);
487 if (n_read == 0 || n_read == SAFE_READ_ERROR)
488 break;
489 tmp->nbytes = n_read;
490 tmp->nlines = 0;
491 tmp->next = NULL;
493 /* Count the number of newlines just read. */
495 char const *buffer_end = tmp->buffer + n_read;
496 char const *p = tmp->buffer;
497 while ((p = memchr (p, '\n', buffer_end - p)))
499 ++p;
500 ++tmp->nlines;
503 total_lines += tmp->nlines;
505 /* If there is enough room in the last buffer read, just append the new
506 one to it. This is because when reading from a pipe, 'n_read' can
507 often be very small. */
508 if (tmp->nbytes + last->nbytes < BUFSIZ)
510 memcpy (&last->buffer[last->nbytes], tmp->buffer, tmp->nbytes);
511 last->nbytes += tmp->nbytes;
512 last->nlines += tmp->nlines;
514 else
516 /* If there's not enough room, link the new buffer onto the end of
517 the list, then either free up the oldest buffer for the next
518 read if that would leave enough lines, or else malloc a new one.
519 Some compaction mechanism is possible but probably not
520 worthwhile. */
521 last = last->next = tmp;
522 if (n_elide < total_lines - first->nlines)
524 fwrite (first->buffer, 1, first->nbytes, stdout);
525 tmp = first;
526 total_lines -= first->nlines;
527 first = first->next;
529 else
530 tmp = xmalloc (sizeof (LBUFFER));
534 free (tmp);
536 if (n_read == SAFE_READ_ERROR)
538 error (0, errno, _("error reading %s"), quote (filename));
539 ok = false;
540 goto free_lbuffers;
543 /* If we read any bytes at all, count the incomplete line
544 on files that don't end with a newline. */
545 if (last->nbytes && last->buffer[last->nbytes - 1] != '\n')
547 ++last->nlines;
548 ++total_lines;
551 for (tmp = first; n_elide < total_lines - tmp->nlines; tmp = tmp->next)
553 fwrite (tmp->buffer, 1, tmp->nbytes, stdout);
554 total_lines -= tmp->nlines;
557 /* Print the first 'total_lines - n_elide' lines of tmp->buffer. */
558 if (n_elide < total_lines)
560 size_t n = total_lines - n_elide;
561 char const *buffer_end = tmp->buffer + tmp->nbytes;
562 char const *p = tmp->buffer;
563 while (n && (p = memchr (p, '\n', buffer_end - p)))
565 ++p;
566 ++tmp->nlines;
567 --n;
569 fwrite (tmp->buffer, 1, p - tmp->buffer, stdout);
572 free_lbuffers:
573 while (first)
575 tmp = first->next;
576 free (first);
577 first = tmp;
579 return ok;
582 /* Output all but the last N_LINES lines of the input stream defined by
583 FD, START_POS, and END_POS.
584 START_POS is the starting position of the read pointer for the file
585 associated with FD (may be nonzero).
586 END_POS is the file offset of EOF (one larger than offset of last byte).
587 Return true upon success.
588 Give a diagnostic and return false upon error.
590 NOTE: this code is very similar to that of tail.c's file_lines function.
591 Unfortunately, factoring out some common core looks like it'd result
592 in a less efficient implementation or a messy interface. */
593 static bool
594 elide_tail_lines_seekable (const char *pretty_filename, int fd,
595 uintmax_t n_lines,
596 off_t start_pos, off_t end_pos)
598 char buffer[BUFSIZ];
599 size_t bytes_read;
600 off_t pos = end_pos;
602 /* Set 'bytes_read' to the size of the last, probably partial, buffer;
603 0 < 'bytes_read' <= 'BUFSIZ'. */
604 bytes_read = (pos - start_pos) % BUFSIZ;
605 if (bytes_read == 0)
606 bytes_read = BUFSIZ;
607 /* Make 'pos' a multiple of 'BUFSIZ' (0 if the file is short), so that all
608 reads will be on block boundaries, which might increase efficiency. */
609 pos -= bytes_read;
610 if (lseek (fd, pos, SEEK_SET) < 0)
612 char offset_buf[INT_BUFSIZE_BOUND (pos)];
613 error (0, errno, _("%s: cannot seek to offset %s"),
614 pretty_filename, offtostr (pos, offset_buf));
615 return false;
617 bytes_read = safe_read (fd, buffer, bytes_read);
618 if (bytes_read == SAFE_READ_ERROR)
620 error (0, errno, _("error reading %s"), quote (pretty_filename));
621 return false;
624 /* Count the incomplete line on files that don't end with a newline. */
625 if (bytes_read && buffer[bytes_read - 1] != '\n')
626 --n_lines;
628 while (1)
630 /* Scan backward, counting the newlines in this bufferfull. */
632 size_t n = bytes_read;
633 while (n)
635 char const *nl;
636 nl = memrchr (buffer, '\n', n);
637 if (nl == NULL)
638 break;
639 n = nl - buffer;
640 if (n_lines-- == 0)
642 /* Found it. */
643 /* If necessary, restore the file pointer and copy
644 input to output up to position, POS. */
645 if (start_pos < pos)
647 enum Copy_fd_status err;
648 if (lseek (fd, start_pos, SEEK_SET) < 0)
650 /* Failed to reposition file pointer. */
651 error (0, errno,
652 "%s: unable to restore file pointer to initial offset",
653 quote (pretty_filename));
654 return false;
657 err = copy_fd (fd, stdout, pos - start_pos);
658 if (err != COPY_FD_OK)
660 diagnose_copy_fd_failure (err, pretty_filename);
661 return false;
665 /* Output the initial portion of the buffer
666 in which we found the desired newline byte.
667 Don't bother testing for failure for such a small amount.
668 Any failure will be detected upon close. */
669 fwrite (buffer, 1, n + 1, stdout);
671 /* Set file pointer to the byte after what we've output. */
672 if (lseek (fd, pos + n + 1, SEEK_SET) < 0)
674 error (0, errno, _("%s: failed to reset file pointer"),
675 quote (pretty_filename));
676 return false;
678 return true;
682 /* Not enough newlines in that bufferfull. */
683 if (pos == start_pos)
685 /* Not enough lines in the file. */
686 return true;
688 pos -= BUFSIZ;
689 if (lseek (fd, pos, SEEK_SET) < 0)
691 char offset_buf[INT_BUFSIZE_BOUND (pos)];
692 error (0, errno, _("%s: cannot seek to offset %s"),
693 pretty_filename, offtostr (pos, offset_buf));
694 return false;
697 bytes_read = safe_read (fd, buffer, BUFSIZ);
698 if (bytes_read == SAFE_READ_ERROR)
700 error (0, errno, _("error reading %s"), quote (pretty_filename));
701 return false;
704 /* FIXME: is this dead code?
705 Consider the test, pos == start_pos, above. */
706 if (bytes_read == 0)
707 return true;
711 /* Print all but the last N_ELIDE lines from the input available
712 via file descriptor FD. Return true upon success.
713 Give a diagnostic and return nonzero upon error. */
715 static bool
716 elide_tail_lines_file (const char *filename, int fd, uintmax_t n_elide)
718 if (!presume_input_pipe)
720 /* Find the offset, OFF, of the Nth newline from the end,
721 but not counting the last byte of the file.
722 If found, write from current position to OFF, inclusive.
723 Otherwise, just return true. */
725 off_t start_pos = lseek (fd, 0, SEEK_CUR);
726 off_t end_pos = lseek (fd, 0, SEEK_END);
727 if (0 <= start_pos && start_pos < end_pos)
729 /* If the file is empty, we're done. */
730 if (end_pos == 0)
731 return true;
733 return elide_tail_lines_seekable (filename, fd, n_elide,
734 start_pos, end_pos);
737 /* lseek failed or the end offset precedes start.
738 Fall through. */
741 return elide_tail_lines_pipe (filename, fd, n_elide);
744 static bool
745 head_bytes (const char *filename, int fd, uintmax_t bytes_to_write)
747 char buffer[BUFSIZ];
748 size_t bytes_to_read = BUFSIZ;
750 while (bytes_to_write)
752 size_t bytes_read;
753 if (bytes_to_write < bytes_to_read)
754 bytes_to_read = bytes_to_write;
755 bytes_read = safe_read (fd, buffer, bytes_to_read);
756 if (bytes_read == SAFE_READ_ERROR)
758 error (0, errno, _("error reading %s"), quote (filename));
759 return false;
761 if (bytes_read == 0)
762 break;
763 if (fwrite (buffer, 1, bytes_read, stdout) < bytes_read)
764 error (EXIT_FAILURE, errno, _("write error"));
765 bytes_to_write -= bytes_read;
767 return true;
770 static bool
771 head_lines (const char *filename, int fd, uintmax_t lines_to_write)
773 char buffer[BUFSIZ];
775 while (lines_to_write)
777 size_t bytes_read = safe_read (fd, buffer, BUFSIZ);
778 size_t bytes_to_write = 0;
780 if (bytes_read == SAFE_READ_ERROR)
782 error (0, errno, _("error reading %s"), quote (filename));
783 return false;
785 if (bytes_read == 0)
786 break;
787 while (bytes_to_write < bytes_read)
788 if (buffer[bytes_to_write++] == '\n' && --lines_to_write == 0)
790 off_t n_bytes_past_EOL = bytes_read - bytes_to_write;
791 /* If we have read more data than that on the specified number
792 of lines, try to seek back to the position we would have
793 gotten to had we been reading one byte at a time. */
794 if (lseek (fd, -n_bytes_past_EOL, SEEK_CUR) < 0)
796 int e = errno;
797 struct stat st;
798 if (fstat (fd, &st) != 0 || S_ISREG (st.st_mode))
799 error (0, e, _("cannot reposition file pointer for %s"),
800 quote (filename));
802 break;
804 if (fwrite (buffer, 1, bytes_to_write, stdout) < bytes_to_write)
805 error (EXIT_FAILURE, errno, _("write error"));
807 return true;
810 static bool
811 head (const char *filename, int fd, uintmax_t n_units, bool count_lines,
812 bool elide_from_end)
814 if (print_headers)
815 write_header (filename);
817 if (elide_from_end)
819 if (count_lines)
821 return elide_tail_lines_file (filename, fd, n_units);
823 else
825 return elide_tail_bytes_file (filename, fd, n_units);
828 if (count_lines)
829 return head_lines (filename, fd, n_units);
830 else
831 return head_bytes (filename, fd, n_units);
834 static bool
835 head_file (const char *filename, uintmax_t n_units, bool count_lines,
836 bool elide_from_end)
838 int fd;
839 bool ok;
840 bool is_stdin = STREQ (filename, "-");
842 if (is_stdin)
844 have_read_stdin = true;
845 fd = STDIN_FILENO;
846 filename = _("standard input");
847 if (O_BINARY && ! isatty (STDIN_FILENO))
848 xfreopen (NULL, "rb", stdin);
850 else
852 fd = open (filename, O_RDONLY | O_BINARY);
853 if (fd < 0)
855 error (0, errno, _("cannot open %s for reading"), quote (filename));
856 return false;
860 ok = head (filename, fd, n_units, count_lines, elide_from_end);
861 if (!is_stdin && close (fd) != 0)
863 error (0, errno, _("closing %s"), quote (filename));
864 return false;
866 return ok;
869 /* Convert a string of decimal digits, N_STRING, with an optional suffinx
870 to an integral value. Upon successful conversion,
871 return that value. If it cannot be converted, give a diagnostic and exit.
872 COUNT_LINES indicates whether N_STRING is a number of bytes or a number
873 of lines. It is used solely to give a more specific diagnostic. */
875 static uintmax_t
876 string_to_integer (bool count_lines, const char *n_string)
878 strtol_error s_err;
879 uintmax_t n;
881 s_err = xstrtoumax (n_string, NULL, 10, &n, "bkKmMGTPEZY0");
883 if (s_err == LONGINT_OVERFLOW)
885 error (EXIT_FAILURE, 0,
886 _("%s: %s is so large that it is not representable"), n_string,
887 count_lines ? _("number of lines") : _("number of bytes"));
890 if (s_err != LONGINT_OK)
892 error (EXIT_FAILURE, 0, "%s: %s", n_string,
893 (count_lines
894 ? _("invalid number of lines")
895 : _("invalid number of bytes")));
898 return n;
902 main (int argc, char **argv)
904 enum header_mode header_mode = multiple_files;
905 bool ok = true;
906 int c;
907 size_t i;
909 /* Number of items to print. */
910 uintmax_t n_units = DEFAULT_NUMBER;
912 /* If true, interpret the numeric argument as the number of lines.
913 Otherwise, interpret it as the number of bytes. */
914 bool count_lines = true;
916 /* Elide the specified number of lines or bytes, counting from
917 the end of the file. */
918 bool elide_from_end = false;
920 /* Initializer for file_list if no file-arguments
921 were specified on the command line. */
922 static char const *const default_file_list[] = {"-", NULL};
923 char const *const *file_list;
925 initialize_main (&argc, &argv);
926 set_program_name (argv[0]);
927 setlocale (LC_ALL, "");
928 bindtextdomain (PACKAGE, LOCALEDIR);
929 textdomain (PACKAGE);
931 atexit (close_stdout);
933 have_read_stdin = false;
935 print_headers = false;
937 if (1 < argc && argv[1][0] == '-' && ISDIGIT (argv[1][1]))
939 char *a = argv[1];
940 char *n_string = ++a;
941 char *end_n_string;
942 char multiplier_char = 0;
944 /* Old option syntax; a dash, one or more digits, and one or
945 more option letters. Move past the number. */
946 do ++a;
947 while (ISDIGIT (*a));
949 /* Pointer to the byte after the last digit. */
950 end_n_string = a;
952 /* Parse any appended option letters. */
953 for (; *a; a++)
955 switch (*a)
957 case 'c':
958 count_lines = false;
959 multiplier_char = 0;
960 break;
962 case 'b':
963 case 'k':
964 case 'm':
965 count_lines = false;
966 multiplier_char = *a;
967 break;
969 case 'l':
970 count_lines = true;
971 break;
973 case 'q':
974 header_mode = never;
975 break;
977 case 'v':
978 header_mode = always;
979 break;
981 default:
982 error (0, 0, _("invalid trailing option -- %c"), *a);
983 usage (EXIT_FAILURE);
987 /* Append the multiplier character (if any) onto the end of
988 the digit string. Then add NUL byte if necessary. */
989 *end_n_string = multiplier_char;
990 if (multiplier_char)
991 *(++end_n_string) = 0;
993 n_units = string_to_integer (count_lines, n_string);
995 /* Make the options we just parsed invisible to getopt. */
996 argv[1] = argv[0];
997 argv++;
998 argc--;
1001 while ((c = getopt_long (argc, argv, "c:n:qv0123456789", long_options, NULL))
1002 != -1)
1004 switch (c)
1006 case PRESUME_INPUT_PIPE_OPTION:
1007 presume_input_pipe = true;
1008 break;
1010 case 'c':
1011 count_lines = false;
1012 elide_from_end = (*optarg == '-');
1013 if (elide_from_end)
1014 ++optarg;
1015 n_units = string_to_integer (count_lines, optarg);
1016 break;
1018 case 'n':
1019 count_lines = true;
1020 elide_from_end = (*optarg == '-');
1021 if (elide_from_end)
1022 ++optarg;
1023 n_units = string_to_integer (count_lines, optarg);
1024 break;
1026 case 'q':
1027 header_mode = never;
1028 break;
1030 case 'v':
1031 header_mode = always;
1032 break;
1034 case_GETOPT_HELP_CHAR;
1036 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
1038 default:
1039 if (ISDIGIT (c))
1040 error (0, 0, _("invalid trailing option -- %c"), c);
1041 usage (EXIT_FAILURE);
1045 if (header_mode == always
1046 || (header_mode == multiple_files && optind < argc - 1))
1047 print_headers = true;
1049 if ( ! count_lines && elide_from_end && OFF_T_MAX < n_units)
1051 char umax_buf[INT_BUFSIZE_BOUND (n_units)];
1052 error (EXIT_FAILURE, 0, _("%s: number of bytes is too large"),
1053 umaxtostr (n_units, umax_buf));
1056 file_list = (optind < argc
1057 ? (char const *const *) &argv[optind]
1058 : default_file_list);
1060 if (O_BINARY && ! isatty (STDOUT_FILENO))
1061 xfreopen (NULL, "wb", stdout);
1063 for (i = 0; file_list[i]; ++i)
1064 ok &= head_file (file_list[i], n_units, count_lines, elide_from_end);
1066 if (have_read_stdin && close (STDIN_FILENO) < 0)
1067 error (EXIT_FAILURE, errno, "-");
1069 exit (ok ? EXIT_SUCCESS : EXIT_FAILURE);