fiemap copy: don't let write failure go unreported; adjust style, etc.
[coreutils.git] / src / head.c
blobb3ac7fdf85b3604356c7176eb01a13a7039f0d78
1 /* head -- output first part of file(s)
2 Copyright (C) 1989-1991, 1995-2006, 2008-2011 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 "xfreopen.h"
40 #include "xstrtol.h"
42 /* The official name of this program (e.g., no `g' prefix). */
43 #define PROGRAM_NAME "head"
45 #define AUTHORS \
46 proper_name ("David MacKenzie"), \
47 proper_name ("Jim Meyering")
49 /* Number of lines/chars/blocks to head. */
50 #define DEFAULT_NUMBER 10
52 /* Useful only when eliding tail bytes or lines.
53 If true, skip the is-regular-file test used to determine whether
54 to use the lseek optimization. Instead, use the more general (and
55 more expensive) code unconditionally. Intended solely for testing. */
56 static bool presume_input_pipe;
58 /* If true, print filename headers. */
59 static bool print_headers;
61 /* When to print the filename banners. */
62 enum header_mode
64 multiple_files, always, never
67 /* Have we ever read standard input? */
68 static bool have_read_stdin;
70 enum Copy_fd_status
72 COPY_FD_OK = 0,
73 COPY_FD_READ_ERROR,
74 COPY_FD_WRITE_ERROR,
75 COPY_FD_UNEXPECTED_EOF
78 /* For long options that have no equivalent short option, use a
79 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
80 enum
82 PRESUME_INPUT_PIPE_OPTION = CHAR_MAX + 1
85 static struct option const long_options[] =
87 {"bytes", required_argument, NULL, 'c'},
88 {"lines", required_argument, NULL, 'n'},
89 {"-presume-input-pipe", no_argument, NULL,
90 PRESUME_INPUT_PIPE_OPTION}, /* do not document */
91 {"quiet", no_argument, NULL, 'q'},
92 {"silent", no_argument, NULL, 'q'},
93 {"verbose", no_argument, NULL, 'v'},
94 {GETOPT_HELP_OPTION_DECL},
95 {GETOPT_VERSION_OPTION_DECL},
96 {NULL, 0, NULL, 0}
99 void
100 usage (int status)
102 if (status != EXIT_SUCCESS)
103 fprintf (stderr, _("Try `%s --help' for more information.\n"),
104 program_name);
105 else
107 printf (_("\
108 Usage: %s [OPTION]... [FILE]...\n\
110 program_name);
111 fputs (_("\
112 Print the first 10 lines of each FILE to standard output.\n\
113 With more than one FILE, precede each with a header giving the file name.\n\
114 With no FILE, or when FILE is -, read standard input.\n\
116 "), stdout);
117 fputs (_("\
118 Mandatory arguments to long options are mandatory for short options too.\n\
119 "), stdout);
120 fputs (_("\
121 -c, --bytes=[-]K print the first K bytes of each file;\n\
122 with the leading `-', print all but the last\n\
123 K bytes of each file\n\
124 -n, --lines=[-]K print the first K lines instead of the first 10;\n\
125 with the leading `-', print all but the last\n\
126 K lines of each file\n\
127 "), stdout);
128 fputs (_("\
129 -q, --quiet, --silent never print headers giving file names\n\
130 -v, --verbose always print headers giving file names\n\
131 "), stdout);
132 fputs (HELP_OPTION_DESCRIPTION, stdout);
133 fputs (VERSION_OPTION_DESCRIPTION, stdout);
134 fputs (_("\
136 K may have a multiplier suffix:\n\
137 b 512, kB 1000, K 1024, MB 1000*1000, M 1024*1024,\n\
138 GB 1000*1000*1000, G 1024*1024*1024, and so on for T, P, E, Z, Y.\n\
139 "), stdout);
140 emit_ancillary_info ();
142 exit (status);
145 static void
146 diagnose_copy_fd_failure (enum Copy_fd_status err, char const *filename)
148 switch (err)
150 case COPY_FD_READ_ERROR:
151 error (0, errno, _("error reading %s"), quote (filename));
152 break;
153 case COPY_FD_WRITE_ERROR:
154 error (0, errno, _("error writing %s"), quote (filename));
155 break;
156 case COPY_FD_UNEXPECTED_EOF:
157 error (0, errno, _("%s: file has shrunk too much"), quote (filename));
158 break;
159 default:
160 abort ();
164 static void
165 write_header (const char *filename)
167 static bool first_file = true;
169 printf ("%s==> %s <==\n", (first_file ? "" : "\n"), filename);
170 first_file = false;
173 /* Copy no more than N_BYTES from file descriptor SRC_FD to O_STREAM.
174 Return an appropriate indication of success or failure. */
176 static enum Copy_fd_status
177 copy_fd (int src_fd, FILE *o_stream, uintmax_t n_bytes)
179 char buf[BUFSIZ];
180 const size_t buf_size = sizeof (buf);
182 /* Copy the file contents. */
183 while (0 < n_bytes)
185 size_t n_to_read = MIN (buf_size, n_bytes);
186 size_t n_read = safe_read (src_fd, buf, n_to_read);
187 if (n_read == SAFE_READ_ERROR)
188 return COPY_FD_READ_ERROR;
190 n_bytes -= n_read;
192 if (n_read == 0 && n_bytes != 0)
193 return COPY_FD_UNEXPECTED_EOF;
195 if (fwrite (buf, 1, n_read, o_stream) < n_read)
196 return COPY_FD_WRITE_ERROR;
199 return COPY_FD_OK;
202 /* Print all but the last N_ELIDE lines from the input available via
203 the non-seekable file descriptor FD. Return true upon success.
204 Give a diagnostic and return false upon error. */
205 static bool
206 elide_tail_bytes_pipe (const char *filename, int fd, uintmax_t n_elide_0)
208 size_t n_elide = n_elide_0;
210 #ifndef HEAD_TAIL_PIPE_READ_BUFSIZE
211 # define HEAD_TAIL_PIPE_READ_BUFSIZE BUFSIZ
212 #endif
213 #define READ_BUFSIZE HEAD_TAIL_PIPE_READ_BUFSIZE
215 /* If we're eliding no more than this many bytes, then it's ok to allocate
216 more memory in order to use a more time-efficient algorithm.
217 FIXME: use a fraction of available memory instead, as in sort.
218 FIXME: is this even worthwhile? */
219 #ifndef HEAD_TAIL_PIPE_BYTECOUNT_THRESHOLD
220 # define HEAD_TAIL_PIPE_BYTECOUNT_THRESHOLD 1024 * 1024
221 #endif
223 #if HEAD_TAIL_PIPE_BYTECOUNT_THRESHOLD < 2 * READ_BUFSIZE
224 "HEAD_TAIL_PIPE_BYTECOUNT_THRESHOLD must be at least 2 * READ_BUFSIZE"
225 #endif
227 if (SIZE_MAX < n_elide_0 + READ_BUFSIZE)
229 char umax_buf[INT_BUFSIZE_BOUND (n_elide_0)];
230 error (EXIT_FAILURE, 0, _("%s: number of bytes is too large"),
231 umaxtostr (n_elide_0, umax_buf));
234 /* Two cases to consider...
235 1) n_elide is small enough that we can afford to double-buffer:
236 allocate 2 * (READ_BUFSIZE + n_elide) bytes
237 2) n_elide is too big for that, so we allocate only
238 (READ_BUFSIZE + n_elide) bytes
240 FIXME: profile, to see if double-buffering is worthwhile
242 CAUTION: do not fail (out of memory) when asked to elide
243 a ridiculous amount, but when given only a small input. */
245 if (n_elide <= HEAD_TAIL_PIPE_BYTECOUNT_THRESHOLD)
247 bool ok = true;
248 bool first = true;
249 bool eof = false;
250 size_t n_to_read = READ_BUFSIZE + n_elide;
251 bool i;
252 char *b[2];
253 b[0] = xnmalloc (2, n_to_read);
254 b[1] = b[0] + n_to_read;
256 for (i = false; ! eof ; i = !i)
258 size_t n_read = full_read (fd, b[i], n_to_read);
259 size_t delta = 0;
260 if (n_read < n_to_read)
262 if (errno != 0)
264 error (0, errno, _("error reading %s"), quote (filename));
265 ok = false;
266 break;
269 /* reached EOF */
270 if (n_read <= n_elide)
272 if (first)
274 /* The input is no larger than the number of bytes
275 to elide. So there's nothing to output, and
276 we're done. */
278 else
280 delta = n_elide - n_read;
283 eof = true;
286 /* Output any (but maybe just part of the) elided data from
287 the previous round. */
288 if ( ! first)
290 /* Don't bother checking for errors here.
291 If there's a failure, the test of the following
292 fwrite or in close_stdout will catch it. */
293 fwrite (b[!i] + READ_BUFSIZE, 1, n_elide - delta, stdout);
295 first = false;
297 if (n_elide < n_read
298 && fwrite (b[i], 1, n_read - n_elide, stdout) < n_read - n_elide)
300 error (0, errno, _("write error"));
301 ok = false;
302 break;
306 free (b[0]);
307 return ok;
309 else
311 /* Read blocks of size READ_BUFSIZE, until we've read at least n_elide
312 bytes. Then, for each new buffer we read, also write an old one. */
314 bool ok = true;
315 bool eof = false;
316 size_t n_read;
317 bool buffered_enough;
318 size_t i, i_next;
319 char **b;
320 /* Round n_elide up to a multiple of READ_BUFSIZE. */
321 size_t rem = READ_BUFSIZE - (n_elide % READ_BUFSIZE);
322 size_t n_elide_round = n_elide + rem;
323 size_t n_bufs = n_elide_round / READ_BUFSIZE + 1;
324 b = xcalloc (n_bufs, sizeof *b);
326 buffered_enough = false;
327 for (i = 0, i_next = 1; !eof; i = i_next, i_next = (i_next + 1) % n_bufs)
329 if (b[i] == NULL)
330 b[i] = xmalloc (READ_BUFSIZE);
331 n_read = full_read (fd, b[i], READ_BUFSIZE);
332 if (n_read < READ_BUFSIZE)
334 if (errno != 0)
336 error (0, errno, _("error reading %s"), quote (filename));
337 ok = false;
338 goto free_mem;
340 eof = true;
343 if (i + 1 == n_bufs)
344 buffered_enough = true;
346 if (buffered_enough)
348 if (fwrite (b[i_next], 1, n_read, stdout) < n_read)
350 error (0, errno, _("write error"));
351 ok = false;
352 goto free_mem;
357 /* Output any remainder: rem bytes from b[i] + n_read. */
358 if (rem)
360 if (buffered_enough)
362 size_t n_bytes_left_in_b_i = READ_BUFSIZE - n_read;
363 if (rem < n_bytes_left_in_b_i)
365 fwrite (b[i] + n_read, 1, rem, stdout);
367 else
369 fwrite (b[i] + n_read, 1, n_bytes_left_in_b_i, stdout);
370 fwrite (b[i_next], 1, rem - n_bytes_left_in_b_i, stdout);
373 else if (i + 1 == n_bufs)
375 /* This happens when n_elide < file_size < n_elide_round.
377 |READ_BUF.|
378 | | rem |
379 |---------!---------!---------!---------|
380 |---- n_elide ---------|
381 | | x |
382 | |y |
383 |---- file size -----------|
384 | |n_read|
385 |---- n_elide_round ----------|
387 size_t y = READ_BUFSIZE - rem;
388 size_t x = n_read - y;
389 fwrite (b[i_next], 1, x, stdout);
393 free_mem:;
394 for (i = 0; i < n_bufs; i++)
395 free (b[i]);
396 free (b);
398 return ok;
402 /* Print all but the last N_ELIDE lines from the input available
403 via file descriptor FD. Return true upon success.
404 Give a diagnostic and return false upon error. */
406 /* NOTE: if the input file shrinks by more than N_ELIDE bytes between
407 the length determination and the actual reading, then head fails. */
409 static bool
410 elide_tail_bytes_file (const char *filename, int fd, uintmax_t n_elide)
412 struct stat stats;
414 if (presume_input_pipe || fstat (fd, &stats) || ! S_ISREG (stats.st_mode))
416 return elide_tail_bytes_pipe (filename, fd, n_elide);
418 else
420 off_t current_pos, end_pos;
421 uintmax_t bytes_remaining;
422 off_t diff;
423 enum Copy_fd_status err;
425 if ((current_pos = lseek (fd, (off_t) 0, SEEK_CUR)) == -1
426 || (end_pos = lseek (fd, (off_t) 0, SEEK_END)) == -1)
428 error (0, errno, _("cannot lseek %s"), quote (filename));
429 return false;
432 /* Be careful here. The current position may actually be
433 beyond the end of the file. */
434 bytes_remaining = (diff = end_pos - current_pos) < 0 ? 0 : diff;
436 if (bytes_remaining <= n_elide)
437 return true;
439 /* Seek back to `current' position, then copy the required
440 number of bytes from fd. */
441 if (lseek (fd, (off_t) 0, current_pos) == -1)
443 error (0, errno, _("%s: cannot lseek back to original position"),
444 quote (filename));
445 return false;
448 err = copy_fd (fd, stdout, bytes_remaining - n_elide);
449 if (err == COPY_FD_OK)
450 return true;
452 diagnose_copy_fd_failure (err, filename);
453 return false;
457 /* Print all but the last N_ELIDE lines from the input stream
458 open for reading via file descriptor FD.
459 Buffer the specified number of lines as a linked list of LBUFFERs,
460 adding them as needed. Return true if successful. */
462 static bool
463 elide_tail_lines_pipe (const char *filename, int fd, uintmax_t n_elide)
465 struct linebuffer
467 char buffer[BUFSIZ];
468 size_t nbytes;
469 size_t nlines;
470 struct linebuffer *next;
472 typedef struct linebuffer LBUFFER;
473 LBUFFER *first, *last, *tmp;
474 size_t total_lines = 0; /* Total number of newlines in all buffers. */
475 bool ok = true;
476 size_t n_read; /* Size in bytes of most recent read */
478 first = last = xmalloc (sizeof (LBUFFER));
479 first->nbytes = first->nlines = 0;
480 first->next = NULL;
481 tmp = xmalloc (sizeof (LBUFFER));
483 /* Always read into a fresh buffer.
484 Read, (producing no output) until we've accumulated at least
485 n_elide newlines, or until EOF, whichever comes first. */
486 while (1)
488 n_read = safe_read (fd, tmp->buffer, BUFSIZ);
489 if (n_read == 0 || n_read == SAFE_READ_ERROR)
490 break;
491 tmp->nbytes = n_read;
492 tmp->nlines = 0;
493 tmp->next = NULL;
495 /* Count the number of newlines just read. */
497 char const *buffer_end = tmp->buffer + n_read;
498 char const *p = tmp->buffer;
499 while ((p = memchr (p, '\n', buffer_end - p)))
501 ++p;
502 ++tmp->nlines;
505 total_lines += tmp->nlines;
507 /* If there is enough room in the last buffer read, just append the new
508 one to it. This is because when reading from a pipe, `n_read' can
509 often be very small. */
510 if (tmp->nbytes + last->nbytes < BUFSIZ)
512 memcpy (&last->buffer[last->nbytes], tmp->buffer, tmp->nbytes);
513 last->nbytes += tmp->nbytes;
514 last->nlines += tmp->nlines;
516 else
518 /* If there's not enough room, link the new buffer onto the end of
519 the list, then either free up the oldest buffer for the next
520 read if that would leave enough lines, or else malloc a new one.
521 Some compaction mechanism is possible but probably not
522 worthwhile. */
523 last = last->next = tmp;
524 if (n_elide < total_lines - first->nlines)
526 fwrite (first->buffer, 1, first->nbytes, stdout);
527 tmp = first;
528 total_lines -= first->nlines;
529 first = first->next;
531 else
532 tmp = xmalloc (sizeof (LBUFFER));
536 free (tmp);
538 if (n_read == SAFE_READ_ERROR)
540 error (0, errno, _("error reading %s"), quote (filename));
541 ok = false;
542 goto free_lbuffers;
545 /* If we read any bytes at all, count the incomplete line
546 on files that don't end with a newline. */
547 if (last->nbytes && last->buffer[last->nbytes - 1] != '\n')
549 ++last->nlines;
550 ++total_lines;
553 for (tmp = first; n_elide < total_lines - tmp->nlines; tmp = tmp->next)
555 fwrite (tmp->buffer, 1, tmp->nbytes, stdout);
556 total_lines -= tmp->nlines;
559 /* Print the first `total_lines - n_elide' lines of tmp->buffer. */
560 if (n_elide < total_lines)
562 size_t n = total_lines - n_elide;
563 char const *buffer_end = tmp->buffer + tmp->nbytes;
564 char const *p = tmp->buffer;
565 while (n && (p = memchr (p, '\n', buffer_end - p)))
567 ++p;
568 ++tmp->nlines;
569 --n;
571 fwrite (tmp->buffer, 1, p - tmp->buffer, stdout);
574 free_lbuffers:
575 while (first)
577 tmp = first->next;
578 free (first);
579 first = tmp;
581 return ok;
584 /* Output all but the last N_LINES lines of the input stream defined by
585 FD, START_POS, and END_POS.
586 START_POS is the starting position of the read pointer for the file
587 associated with FD (may be nonzero).
588 END_POS is the file offset of EOF (one larger than offset of last byte).
589 Return true upon success.
590 Give a diagnostic and return false upon error.
592 NOTE: this code is very similar to that of tail.c's file_lines function.
593 Unfortunately, factoring out some common core looks like it'd result
594 in a less efficient implementation or a messy interface. */
595 static bool
596 elide_tail_lines_seekable (const char *pretty_filename, int fd,
597 uintmax_t n_lines,
598 off_t start_pos, off_t end_pos)
600 char buffer[BUFSIZ];
601 size_t bytes_read;
602 off_t pos = end_pos;
604 /* Set `bytes_read' to the size of the last, probably partial, buffer;
605 0 < `bytes_read' <= `BUFSIZ'. */
606 bytes_read = (pos - start_pos) % BUFSIZ;
607 if (bytes_read == 0)
608 bytes_read = BUFSIZ;
609 /* Make `pos' a multiple of `BUFSIZ' (0 if the file is short), so that all
610 reads will be on block boundaries, which might increase efficiency. */
611 pos -= bytes_read;
612 if (lseek (fd, pos, SEEK_SET) < 0)
614 char offset_buf[INT_BUFSIZE_BOUND (pos)];
615 error (0, errno, _("%s: cannot seek to offset %s"),
616 pretty_filename, offtostr (pos, offset_buf));
617 return false;
619 bytes_read = safe_read (fd, buffer, bytes_read);
620 if (bytes_read == SAFE_READ_ERROR)
622 error (0, errno, _("error reading %s"), quote (pretty_filename));
623 return false;
626 /* Count the incomplete line on files that don't end with a newline. */
627 if (bytes_read && buffer[bytes_read - 1] != '\n')
628 --n_lines;
630 while (1)
632 /* Scan backward, counting the newlines in this bufferfull. */
634 size_t n = bytes_read;
635 while (n)
637 char const *nl;
638 nl = memrchr (buffer, '\n', n);
639 if (nl == NULL)
640 break;
641 n = nl - buffer;
642 if (n_lines-- == 0)
644 /* Found it. */
645 /* If necessary, restore the file pointer and copy
646 input to output up to position, POS. */
647 if (start_pos < pos)
649 enum Copy_fd_status err;
650 if (lseek (fd, start_pos, SEEK_SET) < 0)
652 /* Failed to reposition file pointer. */
653 error (0, errno,
654 "%s: unable to restore file pointer to initial offset",
655 quote (pretty_filename));
656 return false;
659 err = copy_fd (fd, stdout, pos - start_pos);
660 if (err != COPY_FD_OK)
662 diagnose_copy_fd_failure (err, pretty_filename);
663 return false;
667 /* Output the initial portion of the buffer
668 in which we found the desired newline byte.
669 Don't bother testing for failure for such a small amount.
670 Any failure will be detected upon close. */
671 fwrite (buffer, 1, n + 1, stdout);
672 return true;
676 /* Not enough newlines in that bufferfull. */
677 if (pos == start_pos)
679 /* Not enough lines in the file. */
680 return true;
682 pos -= BUFSIZ;
683 if (lseek (fd, pos, SEEK_SET) < 0)
685 char offset_buf[INT_BUFSIZE_BOUND (pos)];
686 error (0, errno, _("%s: cannot seek to offset %s"),
687 pretty_filename, offtostr (pos, offset_buf));
688 return false;
691 bytes_read = safe_read (fd, buffer, BUFSIZ);
692 if (bytes_read == SAFE_READ_ERROR)
694 error (0, errno, _("error reading %s"), quote (pretty_filename));
695 return false;
698 /* FIXME: is this dead code?
699 Consider the test, pos == start_pos, above. */
700 if (bytes_read == 0)
701 return true;
705 /* Print all but the last N_ELIDE lines from the input available
706 via file descriptor FD. Return true upon success.
707 Give a diagnostic and return nonzero upon error. */
709 static bool
710 elide_tail_lines_file (const char *filename, int fd, uintmax_t n_elide)
712 if (!presume_input_pipe)
714 /* Find the offset, OFF, of the Nth newline from the end,
715 but not counting the last byte of the file.
716 If found, write from current position to OFF, inclusive.
717 Otherwise, just return true. */
719 off_t start_pos = lseek (fd, (off_t) 0, SEEK_CUR);
720 off_t end_pos = lseek (fd, (off_t) 0, SEEK_END);
721 if (0 <= start_pos && start_pos < end_pos)
723 /* If the file is empty, we're done. */
724 if (end_pos == 0)
725 return true;
727 return elide_tail_lines_seekable (filename, fd, n_elide,
728 start_pos, end_pos);
731 /* lseek failed or the end offset precedes start.
732 Fall through. */
735 return elide_tail_lines_pipe (filename, fd, n_elide);
738 static bool
739 head_bytes (const char *filename, int fd, uintmax_t bytes_to_write)
741 char buffer[BUFSIZ];
742 size_t bytes_to_read = BUFSIZ;
744 while (bytes_to_write)
746 size_t bytes_read;
747 if (bytes_to_write < bytes_to_read)
748 bytes_to_read = bytes_to_write;
749 bytes_read = safe_read (fd, buffer, bytes_to_read);
750 if (bytes_read == SAFE_READ_ERROR)
752 error (0, errno, _("error reading %s"), quote (filename));
753 return false;
755 if (bytes_read == 0)
756 break;
757 if (fwrite (buffer, 1, bytes_read, stdout) < bytes_read)
758 error (EXIT_FAILURE, errno, _("write error"));
759 bytes_to_write -= bytes_read;
761 return true;
764 static bool
765 head_lines (const char *filename, int fd, uintmax_t lines_to_write)
767 char buffer[BUFSIZ];
769 while (lines_to_write)
771 size_t bytes_read = safe_read (fd, buffer, BUFSIZ);
772 size_t bytes_to_write = 0;
774 if (bytes_read == SAFE_READ_ERROR)
776 error (0, errno, _("error reading %s"), quote (filename));
777 return false;
779 if (bytes_read == 0)
780 break;
781 while (bytes_to_write < bytes_read)
782 if (buffer[bytes_to_write++] == '\n' && --lines_to_write == 0)
784 off_t n_bytes_past_EOL = bytes_read - bytes_to_write;
785 /* If we have read more data than that on the specified number
786 of lines, try to seek back to the position we would have
787 gotten to had we been reading one byte at a time. */
788 if (lseek (fd, -n_bytes_past_EOL, SEEK_CUR) < 0)
790 int e = errno;
791 struct stat st;
792 if (fstat (fd, &st) != 0 || S_ISREG (st.st_mode))
793 error (0, e, _("cannot reposition file pointer for %s"),
794 quote (filename));
796 break;
798 if (fwrite (buffer, 1, bytes_to_write, stdout) < bytes_to_write)
799 error (EXIT_FAILURE, errno, _("write error"));
801 return true;
804 static bool
805 head (const char *filename, int fd, uintmax_t n_units, bool count_lines,
806 bool elide_from_end)
808 if (print_headers)
809 write_header (filename);
811 if (elide_from_end)
813 if (count_lines)
815 return elide_tail_lines_file (filename, fd, n_units);
817 else
819 return elide_tail_bytes_file (filename, fd, n_units);
822 if (count_lines)
823 return head_lines (filename, fd, n_units);
824 else
825 return head_bytes (filename, fd, n_units);
828 static bool
829 head_file (const char *filename, uintmax_t n_units, bool count_lines,
830 bool elide_from_end)
832 int fd;
833 bool ok;
834 bool is_stdin = STREQ (filename, "-");
836 if (is_stdin)
838 have_read_stdin = true;
839 fd = STDIN_FILENO;
840 filename = _("standard input");
841 if (O_BINARY && ! isatty (STDIN_FILENO))
842 xfreopen (NULL, "rb", stdin);
844 else
846 fd = open (filename, O_RDONLY | O_BINARY);
847 if (fd < 0)
849 error (0, errno, _("cannot open %s for reading"), quote (filename));
850 return false;
854 ok = head (filename, fd, n_units, count_lines, elide_from_end);
855 if (!is_stdin && close (fd) != 0)
857 error (0, errno, _("closing %s"), quote (filename));
858 return false;
860 return ok;
863 /* Convert a string of decimal digits, N_STRING, with an optional suffinx
864 to an integral value. Upon successful conversion,
865 return that value. If it cannot be converted, give a diagnostic and exit.
866 COUNT_LINES indicates whether N_STRING is a number of bytes or a number
867 of lines. It is used solely to give a more specific diagnostic. */
869 static uintmax_t
870 string_to_integer (bool count_lines, const char *n_string)
872 strtol_error s_err;
873 uintmax_t n;
875 s_err = xstrtoumax (n_string, NULL, 10, &n, "bkKmMGTPEZY0");
877 if (s_err == LONGINT_OVERFLOW)
879 error (EXIT_FAILURE, 0,
880 _("%s: %s is so large that it is not representable"), n_string,
881 count_lines ? _("number of lines") : _("number of bytes"));
884 if (s_err != LONGINT_OK)
886 error (EXIT_FAILURE, 0, "%s: %s", n_string,
887 (count_lines
888 ? _("invalid number of lines")
889 : _("invalid number of bytes")));
892 return n;
896 main (int argc, char **argv)
898 enum header_mode header_mode = multiple_files;
899 bool ok = true;
900 int c;
901 size_t i;
903 /* Number of items to print. */
904 uintmax_t n_units = DEFAULT_NUMBER;
906 /* If true, interpret the numeric argument as the number of lines.
907 Otherwise, interpret it as the number of bytes. */
908 bool count_lines = true;
910 /* Elide the specified number of lines or bytes, counting from
911 the end of the file. */
912 bool elide_from_end = false;
914 /* Initializer for file_list if no file-arguments
915 were specified on the command line. */
916 static char const *const default_file_list[] = {"-", NULL};
917 char const *const *file_list;
919 initialize_main (&argc, &argv);
920 set_program_name (argv[0]);
921 setlocale (LC_ALL, "");
922 bindtextdomain (PACKAGE, LOCALEDIR);
923 textdomain (PACKAGE);
925 atexit (close_stdout);
927 have_read_stdin = false;
929 print_headers = false;
931 if (1 < argc && argv[1][0] == '-' && ISDIGIT (argv[1][1]))
933 char *a = argv[1];
934 char *n_string = ++a;
935 char *end_n_string;
936 char multiplier_char = 0;
938 /* Old option syntax; a dash, one or more digits, and one or
939 more option letters. Move past the number. */
940 do ++a;
941 while (ISDIGIT (*a));
943 /* Pointer to the byte after the last digit. */
944 end_n_string = a;
946 /* Parse any appended option letters. */
947 for (; *a; a++)
949 switch (*a)
951 case 'c':
952 count_lines = false;
953 multiplier_char = 0;
954 break;
956 case 'b':
957 case 'k':
958 case 'm':
959 count_lines = false;
960 multiplier_char = *a;
961 break;
963 case 'l':
964 count_lines = true;
965 break;
967 case 'q':
968 header_mode = never;
969 break;
971 case 'v':
972 header_mode = always;
973 break;
975 default:
976 error (0, 0, _("invalid trailing option -- %c"), *a);
977 usage (EXIT_FAILURE);
981 /* Append the multiplier character (if any) onto the end of
982 the digit string. Then add NUL byte if necessary. */
983 *end_n_string = multiplier_char;
984 if (multiplier_char)
985 *(++end_n_string) = 0;
987 n_units = string_to_integer (count_lines, n_string);
989 /* Make the options we just parsed invisible to getopt. */
990 argv[1] = argv[0];
991 argv++;
992 argc--;
995 while ((c = getopt_long (argc, argv, "c:n:qv0123456789", long_options, NULL))
996 != -1)
998 switch (c)
1000 case PRESUME_INPUT_PIPE_OPTION:
1001 presume_input_pipe = true;
1002 break;
1004 case 'c':
1005 count_lines = false;
1006 elide_from_end = (*optarg == '-');
1007 if (elide_from_end)
1008 ++optarg;
1009 n_units = string_to_integer (count_lines, optarg);
1010 break;
1012 case 'n':
1013 count_lines = true;
1014 elide_from_end = (*optarg == '-');
1015 if (elide_from_end)
1016 ++optarg;
1017 n_units = string_to_integer (count_lines, optarg);
1018 break;
1020 case 'q':
1021 header_mode = never;
1022 break;
1024 case 'v':
1025 header_mode = always;
1026 break;
1028 case_GETOPT_HELP_CHAR;
1030 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
1032 default:
1033 if (ISDIGIT (c))
1034 error (0, 0, _("invalid trailing option -- %c"), c);
1035 usage (EXIT_FAILURE);
1039 if (header_mode == always
1040 || (header_mode == multiple_files && optind < argc - 1))
1041 print_headers = true;
1043 if ( ! count_lines && elide_from_end && OFF_T_MAX < n_units)
1045 char umax_buf[INT_BUFSIZE_BOUND (n_units)];
1046 error (EXIT_FAILURE, 0, _("%s: number of bytes is too large"),
1047 umaxtostr (n_units, umax_buf));
1050 file_list = (optind < argc
1051 ? (char const *const *) &argv[optind]
1052 : default_file_list);
1054 if (O_BINARY && ! isatty (STDOUT_FILENO))
1055 xfreopen (NULL, "wb", stdout);
1057 for (i = 0; file_list[i]; ++i)
1058 ok &= head_file (file_list[i], n_units, count_lines, elide_from_end);
1060 if (have_read_stdin && close (STDIN_FILENO) < 0)
1061 error (EXIT_FAILURE, errno, "-");
1063 exit (ok ? EXIT_SUCCESS : EXIT_FAILURE);