tests: ensure touch honors trailing slash
[coreutils/ericb.git] / src / head.c
blob9080168bc0542f37a2c901044418dbafda7010d1
1 /* head -- output first part of file(s)
2 Copyright (C) 89, 90, 91, 1995-2006, 2008-2009 Free Software
3 Foundation, Inc.
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, either version 3 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. */
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>
33 #include "system.h"
35 #include "error.h"
36 #include "full-write.h"
37 #include "full-read.h"
38 #include "quote.h"
39 #include "safe-read.h"
40 #include "xfreopen.h"
41 #include "xstrtol.h"
43 /* The official name of this program (e.g., no `g' prefix). */
44 #define PROGRAM_NAME "head"
46 #define AUTHORS \
47 proper_name ("David MacKenzie"), \
48 proper_name ("Jim Meyering")
50 /* Number of lines/chars/blocks to head. */
51 #define DEFAULT_NUMBER 10
53 /* Useful only when eliding tail bytes or lines.
54 If true, skip the is-regular-file test used to determine whether
55 to use the lseek optimization. Instead, use the more general (and
56 more expensive) code unconditionally. Intended solely for testing. */
57 static bool presume_input_pipe;
59 /* If true, print filename headers. */
60 static bool print_headers;
62 /* When to print the filename banners. */
63 enum header_mode
65 multiple_files, always, never
68 /* Have we ever read standard input? */
69 static bool have_read_stdin;
71 enum Copy_fd_status
73 COPY_FD_OK = 0,
74 COPY_FD_READ_ERROR,
75 COPY_FD_WRITE_ERROR,
76 COPY_FD_UNEXPECTED_EOF
79 /* For long options that have no equivalent short option, use a
80 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
81 enum
83 PRESUME_INPUT_PIPE_OPTION = CHAR_MAX + 1
86 static struct option const long_options[] =
88 {"bytes", required_argument, NULL, 'c'},
89 {"lines", required_argument, NULL, 'n'},
90 {"-presume-input-pipe", no_argument, NULL,
91 PRESUME_INPUT_PIPE_OPTION}, /* do not document */
92 {"quiet", no_argument, NULL, 'q'},
93 {"silent", no_argument, NULL, 'q'},
94 {"verbose", no_argument, NULL, 'v'},
95 {GETOPT_HELP_OPTION_DECL},
96 {GETOPT_VERSION_OPTION_DECL},
97 {NULL, 0, NULL, 0}
100 void
101 usage (int status)
103 if (status != EXIT_SUCCESS)
104 fprintf (stderr, _("Try `%s --help' for more information.\n"),
105 program_name);
106 else
108 printf (_("\
109 Usage: %s [OPTION]... [FILE]...\n\
111 program_name);
112 fputs (_("\
113 Print the first 10 lines of each FILE to standard output.\n\
114 With more than one FILE, precede each with a header giving the file name.\n\
115 With no FILE, or when FILE is -, read standard input.\n\
117 "), stdout);
118 fputs (_("\
119 Mandatory arguments to long options are mandatory for short options too.\n\
120 "), stdout);
121 fputs (_("\
122 -c, --bytes=[-]K print the first K bytes of each file;\n\
123 with the leading `-', print all but the last\n\
124 K bytes of each file\n\
125 -n, --lines=[-]K print the first K lines instead of the first 10;\n\
126 with the leading `-', print all but the last\n\
127 K lines of each file\n\
128 "), stdout);
129 fputs (_("\
130 -q, --quiet, --silent never print headers giving file names\n\
131 -v, --verbose always print headers giving file names\n\
132 "), stdout);
133 fputs (HELP_OPTION_DESCRIPTION, stdout);
134 fputs (VERSION_OPTION_DESCRIPTION, stdout);
135 fputs (_("\
137 K may have a multiplier suffix:\n\
138 b 512, kB 1000, K 1024, MB 1000*1000, M 1024*1024,\n\
139 GB 1000*1000*1000, G 1024*1024*1024, and so on for T, P, E, Z, Y.\n\
140 "), stdout);
141 emit_ancillary_info ();
143 exit (status);
146 static void
147 diagnose_copy_fd_failure (enum Copy_fd_status err, char const *filename)
149 switch (err)
151 case COPY_FD_READ_ERROR:
152 error (0, errno, _("error reading %s"), quote (filename));
153 break;
154 case COPY_FD_WRITE_ERROR:
155 error (0, errno, _("error writing %s"), quote (filename));
156 break;
157 case COPY_FD_UNEXPECTED_EOF:
158 error (0, errno, _("%s: file has shrunk too much"), quote (filename));
159 break;
160 default:
161 abort ();
165 static void
166 write_header (const char *filename)
168 static bool first_file = true;
170 printf ("%s==> %s <==\n", (first_file ? "" : "\n"), filename);
171 first_file = false;
174 /* Copy no more than N_BYTES from file descriptor SRC_FD to O_STREAM.
175 Return an appropriate indication of success or failure. */
177 static enum Copy_fd_status
178 copy_fd (int src_fd, FILE *o_stream, uintmax_t n_bytes)
180 char buf[BUFSIZ];
181 const size_t buf_size = sizeof (buf);
183 /* Copy the file contents. */
184 while (0 < n_bytes)
186 size_t n_to_read = MIN (buf_size, n_bytes);
187 size_t n_read = safe_read (src_fd, buf, n_to_read);
188 if (n_read == SAFE_READ_ERROR)
189 return COPY_FD_READ_ERROR;
191 n_bytes -= n_read;
193 if (n_read == 0 && n_bytes != 0)
194 return COPY_FD_UNEXPECTED_EOF;
196 if (fwrite (buf, 1, n_read, o_stream) < n_read)
197 return COPY_FD_WRITE_ERROR;
200 return COPY_FD_OK;
203 /* Print all but the last N_ELIDE lines from the input available via
204 the non-seekable file descriptor FD. Return true upon success.
205 Give a diagnostic and return false upon error. */
206 static bool
207 elide_tail_bytes_pipe (const char *filename, int fd, uintmax_t n_elide_0)
209 size_t n_elide = n_elide_0;
211 #ifndef HEAD_TAIL_PIPE_READ_BUFSIZE
212 # define HEAD_TAIL_PIPE_READ_BUFSIZE BUFSIZ
213 #endif
214 #define READ_BUFSIZE HEAD_TAIL_PIPE_READ_BUFSIZE
216 /* If we're eliding no more than this many bytes, then it's ok to allocate
217 more memory in order to use a more time-efficient algorithm.
218 FIXME: use a fraction of available memory instead, as in sort.
219 FIXME: is this even worthwhile? */
220 #ifndef HEAD_TAIL_PIPE_BYTECOUNT_THRESHOLD
221 # define HEAD_TAIL_PIPE_BYTECOUNT_THRESHOLD 1024 * 1024
222 #endif
224 #if HEAD_TAIL_PIPE_BYTECOUNT_THRESHOLD < 2 * READ_BUFSIZE
225 "HEAD_TAIL_PIPE_BYTECOUNT_THRESHOLD must be at least 2 * READ_BUFSIZE"
226 #endif
228 if (SIZE_MAX < n_elide_0 + READ_BUFSIZE)
230 char umax_buf[INT_BUFSIZE_BOUND (uintmax_t)];
231 error (EXIT_FAILURE, 0, _("%s: number of bytes is too large"),
232 umaxtostr (n_elide_0, umax_buf));
235 /* Two cases to consider...
236 1) n_elide is small enough that we can afford to double-buffer:
237 allocate 2 * (READ_BUFSIZE + n_elide) bytes
238 2) n_elide is too big for that, so we allocate only
239 (READ_BUFSIZE + n_elide) bytes
241 FIXME: profile, to see if double-buffering is worthwhile
243 CAUTION: do not fail (out of memory) when asked to elide
244 a ridiculous amount, but when given only a small input. */
246 if (n_elide <= HEAD_TAIL_PIPE_BYTECOUNT_THRESHOLD)
248 bool ok = true;
249 bool first = true;
250 bool eof = false;
251 size_t n_to_read = READ_BUFSIZE + n_elide;
252 bool i;
253 char *b[2];
254 b[0] = xnmalloc (2, n_to_read);
255 b[1] = b[0] + n_to_read;
257 for (i = false; ! eof ; i = !i)
259 size_t n_read = full_read (fd, b[i], n_to_read);
260 size_t delta = 0;
261 if (n_read < n_to_read)
263 if (errno != 0)
265 error (0, errno, _("error reading %s"), quote (filename));
266 ok = false;
267 break;
270 /* reached EOF */
271 if (n_read <= n_elide)
273 if (first)
275 /* The input is no larger than the number of bytes
276 to elide. So there's nothing to output, and
277 we're done. */
279 else
281 delta = n_elide - n_read;
284 eof = true;
287 /* Output any (but maybe just part of the) elided data from
288 the previous round. */
289 if ( ! first)
291 /* Don't bother checking for errors here.
292 If there's a failure, the test of the following
293 fwrite or in close_stdout will catch it. */
294 fwrite (b[!i] + READ_BUFSIZE, 1, n_elide - delta, stdout);
296 first = false;
298 if (n_elide < n_read
299 && fwrite (b[i], 1, n_read - n_elide, stdout) < n_read - n_elide)
301 error (0, errno, _("write error"));
302 ok = false;
303 break;
307 free (b[0]);
308 return ok;
310 else
312 /* Read blocks of size READ_BUFSIZE, until we've read at least n_elide
313 bytes. Then, for each new buffer we read, also write an old one. */
315 bool ok = true;
316 bool eof = false;
317 size_t n_read;
318 bool buffered_enough;
319 size_t i, i_next;
320 char **b;
321 /* Round n_elide up to a multiple of READ_BUFSIZE. */
322 size_t rem = READ_BUFSIZE - (n_elide % READ_BUFSIZE);
323 size_t n_elide_round = n_elide + rem;
324 size_t n_bufs = n_elide_round / READ_BUFSIZE + 1;
325 b = xcalloc (n_bufs, sizeof *b);
327 buffered_enough = false;
328 for (i = 0, i_next = 1; !eof; i = i_next, i_next = (i_next + 1) % n_bufs)
330 if (b[i] == NULL)
331 b[i] = xmalloc (READ_BUFSIZE);
332 n_read = full_read (fd, b[i], READ_BUFSIZE);
333 if (n_read < READ_BUFSIZE)
335 if (errno != 0)
337 error (0, errno, _("error reading %s"), quote (filename));
338 ok = false;
339 goto free_mem;
341 eof = true;
344 if (i + 1 == n_bufs)
345 buffered_enough = true;
347 if (buffered_enough)
349 if (fwrite (b[i_next], 1, n_read, stdout) < n_read)
351 error (0, errno, _("write error"));
352 ok = false;
353 goto free_mem;
358 /* Output any remainder: rem bytes from b[i] + n_read. */
359 if (rem)
361 if (buffered_enough)
363 size_t n_bytes_left_in_b_i = READ_BUFSIZE - n_read;
364 if (rem < n_bytes_left_in_b_i)
366 fwrite (b[i] + n_read, 1, rem, stdout);
368 else
370 fwrite (b[i] + n_read, 1, n_bytes_left_in_b_i, stdout);
371 fwrite (b[i_next], 1, rem - n_bytes_left_in_b_i, stdout);
374 else if (i + 1 == n_bufs)
376 /* This happens when n_elide < file_size < n_elide_round.
378 |READ_BUF.|
379 | | rem |
380 |---------!---------!---------!---------|
381 |---- n_elide ---------|
382 | | x |
383 | |y |
384 |---- file size -----------|
385 | |n_read|
386 |---- n_elide_round ----------|
388 size_t y = READ_BUFSIZE - rem;
389 size_t x = n_read - y;
390 fwrite (b[i_next], 1, x, stdout);
394 free_mem:;
395 for (i = 0; i < n_bufs; i++)
396 free (b[i]);
397 free (b);
399 return ok;
403 /* Print all but the last N_ELIDE lines from the input available
404 via file descriptor FD. Return true upon success.
405 Give a diagnostic and return false upon error. */
407 /* NOTE: if the input file shrinks by more than N_ELIDE bytes between
408 the length determination and the actual reading, then head fails. */
410 static bool
411 elide_tail_bytes_file (const char *filename, int fd, uintmax_t n_elide)
413 struct stat stats;
415 if (presume_input_pipe || fstat (fd, &stats) || ! S_ISREG (stats.st_mode))
417 return elide_tail_bytes_pipe (filename, fd, n_elide);
419 else
421 off_t current_pos, end_pos;
422 uintmax_t bytes_remaining;
423 off_t diff;
424 enum Copy_fd_status err;
426 if ((current_pos = lseek (fd, (off_t) 0, SEEK_CUR)) == -1
427 || (end_pos = lseek (fd, (off_t) 0, SEEK_END)) == -1)
429 error (0, errno, _("cannot lseek %s"), quote (filename));
430 return false;
433 /* Be careful here. The current position may actually be
434 beyond the end of the file. */
435 bytes_remaining = (diff = end_pos - current_pos) < 0 ? 0 : diff;
437 if (bytes_remaining <= n_elide)
438 return true;
440 /* Seek back to `current' position, then copy the required
441 number of bytes from fd. */
442 if (lseek (fd, (off_t) 0, current_pos) == -1)
444 error (0, errno, _("%s: cannot lseek back to original position"),
445 quote (filename));
446 return false;
449 err = copy_fd (fd, stdout, bytes_remaining - n_elide);
450 if (err == COPY_FD_OK)
451 return true;
453 diagnose_copy_fd_failure (err, filename);
454 return false;
458 /* Print all but the last N_ELIDE lines from the input stream
459 open for reading via file descriptor FD.
460 Buffer the specified number of lines as a linked list of LBUFFERs,
461 adding them as needed. Return true if successful. */
463 static bool
464 elide_tail_lines_pipe (const char *filename, int fd, uintmax_t n_elide)
466 struct linebuffer
468 char buffer[BUFSIZ];
469 size_t nbytes;
470 size_t nlines;
471 struct linebuffer *next;
473 typedef struct linebuffer LBUFFER;
474 LBUFFER *first, *last, *tmp;
475 size_t total_lines = 0; /* Total number of newlines in all buffers. */
476 bool ok = true;
477 size_t n_read; /* Size in bytes of most recent read */
479 first = last = xmalloc (sizeof (LBUFFER));
480 first->nbytes = first->nlines = 0;
481 first->next = NULL;
482 tmp = xmalloc (sizeof (LBUFFER));
484 /* Always read into a fresh buffer.
485 Read, (producing no output) until we've accumulated at least
486 n_elide newlines, or until EOF, whichever comes first. */
487 while (1)
489 n_read = safe_read (fd, tmp->buffer, BUFSIZ);
490 if (n_read == 0 || n_read == SAFE_READ_ERROR)
491 break;
492 tmp->nbytes = n_read;
493 tmp->nlines = 0;
494 tmp->next = NULL;
496 /* Count the number of newlines just read. */
498 char const *buffer_end = tmp->buffer + n_read;
499 char const *p = tmp->buffer;
500 while ((p = memchr (p, '\n', buffer_end - p)))
502 ++p;
503 ++tmp->nlines;
506 total_lines += tmp->nlines;
508 /* If there is enough room in the last buffer read, just append the new
509 one to it. This is because when reading from a pipe, `n_read' can
510 often be very small. */
511 if (tmp->nbytes + last->nbytes < BUFSIZ)
513 memcpy (&last->buffer[last->nbytes], tmp->buffer, tmp->nbytes);
514 last->nbytes += tmp->nbytes;
515 last->nlines += tmp->nlines;
517 else
519 /* If there's not enough room, link the new buffer onto the end of
520 the list, then either free up the oldest buffer for the next
521 read if that would leave enough lines, or else malloc a new one.
522 Some compaction mechanism is possible but probably not
523 worthwhile. */
524 last = last->next = tmp;
525 if (n_elide < total_lines - first->nlines)
527 fwrite (first->buffer, 1, first->nbytes, stdout);
528 tmp = first;
529 total_lines -= first->nlines;
530 first = first->next;
532 else
533 tmp = xmalloc (sizeof (LBUFFER));
537 free (tmp);
539 if (n_read == SAFE_READ_ERROR)
541 error (0, errno, _("error reading %s"), quote (filename));
542 ok = false;
543 goto free_lbuffers;
546 /* If we read any bytes at all, count the incomplete line
547 on files that don't end with a newline. */
548 if (last->nbytes && last->buffer[last->nbytes - 1] != '\n')
550 ++last->nlines;
551 ++total_lines;
554 for (tmp = first; n_elide < total_lines - tmp->nlines; tmp = tmp->next)
556 fwrite (tmp->buffer, 1, tmp->nbytes, stdout);
557 total_lines -= tmp->nlines;
560 /* Print the first `total_lines - n_elide' lines of tmp->buffer. */
561 if (n_elide < total_lines)
563 size_t n = total_lines - n_elide;
564 char const *buffer_end = tmp->buffer + tmp->nbytes;
565 char const *p = tmp->buffer;
566 while (n && (p = memchr (p, '\n', buffer_end - p)))
568 ++p;
569 ++tmp->nlines;
570 --n;
572 fwrite (tmp->buffer, 1, p - tmp->buffer, stdout);
575 free_lbuffers:
576 while (first)
578 tmp = first->next;
579 free (first);
580 first = tmp;
582 return ok;
585 /* Output all but the last N_LINES lines of the input stream defined by
586 FD, START_POS, and END_POS.
587 START_POS is the starting position of the read pointer for the file
588 associated with FD (may be nonzero).
589 END_POS is the file offset of EOF (one larger than offset of last byte).
590 Return true upon success.
591 Give a diagnostic and return false upon error.
593 NOTE: this code is very similar to that of tail.c's file_lines function.
594 Unfortunately, factoring out some common core looks like it'd result
595 in a less efficient implementation or a messy interface. */
596 static bool
597 elide_tail_lines_seekable (const char *pretty_filename, int fd,
598 uintmax_t n_lines,
599 off_t start_pos, off_t end_pos)
601 char buffer[BUFSIZ];
602 size_t bytes_read;
603 off_t pos = end_pos;
605 /* Set `bytes_read' to the size of the last, probably partial, buffer;
606 0 < `bytes_read' <= `BUFSIZ'. */
607 bytes_read = (pos - start_pos) % BUFSIZ;
608 if (bytes_read == 0)
609 bytes_read = BUFSIZ;
610 /* Make `pos' a multiple of `BUFSIZ' (0 if the file is short), so that all
611 reads will be on block boundaries, which might increase efficiency. */
612 pos -= bytes_read;
613 if (lseek (fd, pos, SEEK_SET) < 0)
615 char offset_buf[INT_BUFSIZE_BOUND (off_t)];
616 error (0, errno, _("%s: cannot seek to offset %s"),
617 pretty_filename, offtostr (pos, offset_buf));
618 return false;
620 bytes_read = safe_read (fd, buffer, bytes_read);
621 if (bytes_read == SAFE_READ_ERROR)
623 error (0, errno, _("error reading %s"), quote (pretty_filename));
624 return false;
627 /* Count the incomplete line on files that don't end with a newline. */
628 if (bytes_read && buffer[bytes_read - 1] != '\n')
629 --n_lines;
631 while (1)
633 /* Scan backward, counting the newlines in this bufferfull. */
635 size_t n = bytes_read;
636 while (n)
638 char const *nl;
639 nl = memrchr (buffer, '\n', n);
640 if (nl == NULL)
641 break;
642 n = nl - buffer;
643 if (n_lines-- == 0)
645 /* Found it. */
646 /* If necessary, restore the file pointer and copy
647 input to output up to position, POS. */
648 if (start_pos < pos)
650 enum Copy_fd_status err;
651 if (lseek (fd, start_pos, SEEK_SET) < 0)
653 /* Failed to reposition file pointer. */
654 error (0, errno,
655 "%s: unable to restore file pointer to initial offset",
656 quote (pretty_filename));
657 return false;
660 err = copy_fd (fd, stdout, pos - start_pos);
661 if (err != COPY_FD_OK)
663 diagnose_copy_fd_failure (err, pretty_filename);
664 return false;
668 /* Output the initial portion of the buffer
669 in which we found the desired newline byte.
670 Don't bother testing for failure for such a small amount.
671 Any failure will be detected upon close. */
672 fwrite (buffer, 1, n + 1, stdout);
673 return true;
677 /* Not enough newlines in that bufferfull. */
678 if (pos == start_pos)
680 /* Not enough lines in the file. */
681 return true;
683 pos -= BUFSIZ;
684 if (lseek (fd, pos, SEEK_SET) < 0)
686 char offset_buf[INT_BUFSIZE_BOUND (off_t)];
687 error (0, errno, _("%s: cannot seek to offset %s"),
688 pretty_filename, offtostr (pos, offset_buf));
689 return false;
692 bytes_read = safe_read (fd, buffer, BUFSIZ);
693 if (bytes_read == SAFE_READ_ERROR)
695 error (0, errno, _("error reading %s"), quote (pretty_filename));
696 return false;
699 /* FIXME: is this dead code?
700 Consider the test, pos == start_pos, above. */
701 if (bytes_read == 0)
702 return true;
706 /* Print all but the last N_ELIDE lines from the input available
707 via file descriptor FD. Return true upon success.
708 Give a diagnostic and return nonzero upon error. */
710 static bool
711 elide_tail_lines_file (const char *filename, int fd, uintmax_t n_elide)
713 if (!presume_input_pipe)
715 /* Find the offset, OFF, of the Nth newline from the end,
716 but not counting the last byte of the file.
717 If found, write from current position to OFF, inclusive.
718 Otherwise, just return true. */
720 off_t start_pos = lseek (fd, (off_t) 0, SEEK_CUR);
721 off_t end_pos = lseek (fd, (off_t) 0, SEEK_END);
722 if (0 <= start_pos && start_pos < end_pos)
724 /* If the file is empty, we're done. */
725 if (end_pos == 0)
726 return true;
728 return elide_tail_lines_seekable (filename, fd, n_elide,
729 start_pos, end_pos);
732 /* lseek failed or the end offset precedes start.
733 Fall through. */
736 return elide_tail_lines_pipe (filename, fd, n_elide);
739 static bool
740 head_bytes (const char *filename, int fd, uintmax_t bytes_to_write)
742 char buffer[BUFSIZ];
743 size_t bytes_to_read = BUFSIZ;
745 while (bytes_to_write)
747 size_t bytes_read;
748 if (bytes_to_write < bytes_to_read)
749 bytes_to_read = bytes_to_write;
750 bytes_read = safe_read (fd, buffer, bytes_to_read);
751 if (bytes_read == SAFE_READ_ERROR)
753 error (0, errno, _("error reading %s"), quote (filename));
754 return false;
756 if (bytes_read == 0)
757 break;
758 if (fwrite (buffer, 1, bytes_read, stdout) < bytes_read)
759 error (EXIT_FAILURE, errno, _("write error"));
760 bytes_to_write -= bytes_read;
762 return true;
765 static bool
766 head_lines (const char *filename, int fd, uintmax_t lines_to_write)
768 char buffer[BUFSIZ];
770 while (lines_to_write)
772 size_t bytes_read = safe_read (fd, buffer, BUFSIZ);
773 size_t bytes_to_write = 0;
775 if (bytes_read == SAFE_READ_ERROR)
777 error (0, errno, _("error reading %s"), quote (filename));
778 return false;
780 if (bytes_read == 0)
781 break;
782 while (bytes_to_write < bytes_read)
783 if (buffer[bytes_to_write++] == '\n' && --lines_to_write == 0)
785 off_t n_bytes_past_EOL = bytes_read - bytes_to_write;
786 /* If we have read more data than that on the specified number
787 of lines, try to seek back to the position we would have
788 gotten to had we been reading one byte at a time. */
789 if (lseek (fd, -n_bytes_past_EOL, SEEK_CUR) < 0)
791 int e = errno;
792 struct stat st;
793 if (fstat (fd, &st) != 0 || S_ISREG (st.st_mode))
794 error (0, e, _("cannot reposition file pointer for %s"),
795 quote (filename));
797 break;
799 if (fwrite (buffer, 1, bytes_to_write, stdout) < bytes_to_write)
800 error (EXIT_FAILURE, errno, _("write error"));
802 return true;
805 static bool
806 head (const char *filename, int fd, uintmax_t n_units, bool count_lines,
807 bool elide_from_end)
809 if (print_headers)
810 write_header (filename);
812 if (elide_from_end)
814 if (count_lines)
816 return elide_tail_lines_file (filename, fd, n_units);
818 else
820 return elide_tail_bytes_file (filename, fd, n_units);
823 if (count_lines)
824 return head_lines (filename, fd, n_units);
825 else
826 return head_bytes (filename, fd, n_units);
829 static bool
830 head_file (const char *filename, uintmax_t n_units, bool count_lines,
831 bool elide_from_end)
833 int fd;
834 bool ok;
835 bool is_stdin = STREQ (filename, "-");
837 if (is_stdin)
839 have_read_stdin = true;
840 fd = STDIN_FILENO;
841 filename = _("standard input");
842 if (O_BINARY && ! isatty (STDIN_FILENO))
843 xfreopen (NULL, "rb", stdin);
845 else
847 fd = open (filename, O_RDONLY | O_BINARY);
848 if (fd < 0)
850 error (0, errno, _("cannot open %s for reading"), quote (filename));
851 return false;
855 ok = head (filename, fd, n_units, count_lines, elide_from_end);
856 if (!is_stdin && close (fd) != 0)
858 error (0, errno, _("closing %s"), quote (filename));
859 return false;
861 return ok;
864 /* Convert a string of decimal digits, N_STRING, with an optional suffinx
865 to an integral value. Upon successful conversion,
866 return that value. If it cannot be converted, give a diagnostic and exit.
867 COUNT_LINES indicates whether N_STRING is a number of bytes or a number
868 of lines. It is used solely to give a more specific diagnostic. */
870 static uintmax_t
871 string_to_integer (bool count_lines, const char *n_string)
873 strtol_error s_err;
874 uintmax_t n;
876 s_err = xstrtoumax (n_string, NULL, 10, &n, "bkKmMGTPEZY0");
878 if (s_err == LONGINT_OVERFLOW)
880 error (EXIT_FAILURE, 0,
881 _("%s: %s is so large that it is not representable"), n_string,
882 count_lines ? _("number of lines") : _("number of bytes"));
885 if (s_err != LONGINT_OK)
887 error (EXIT_FAILURE, 0, "%s: %s", n_string,
888 (count_lines
889 ? _("invalid number of lines")
890 : _("invalid number of bytes")));
893 return n;
897 main (int argc, char **argv)
899 enum header_mode header_mode = multiple_files;
900 bool ok = true;
901 int c;
902 size_t i;
904 /* Number of items to print. */
905 uintmax_t n_units = DEFAULT_NUMBER;
907 /* If true, interpret the numeric argument as the number of lines.
908 Otherwise, interpret it as the number of bytes. */
909 bool count_lines = true;
911 /* Elide the specified number of lines or bytes, counting from
912 the end of the file. */
913 bool elide_from_end = false;
915 /* Initializer for file_list if no file-arguments
916 were specified on the command line. */
917 static char const *const default_file_list[] = {"-", NULL};
918 char const *const *file_list;
920 initialize_main (&argc, &argv);
921 set_program_name (argv[0]);
922 setlocale (LC_ALL, "");
923 bindtextdomain (PACKAGE, LOCALEDIR);
924 textdomain (PACKAGE);
926 atexit (close_stdout);
928 have_read_stdin = false;
930 print_headers = false;
932 if (1 < argc && argv[1][0] == '-' && ISDIGIT (argv[1][1]))
934 char *a = argv[1];
935 char *n_string = ++a;
936 char *end_n_string;
937 char multiplier_char = 0;
939 /* Old option syntax; a dash, one or more digits, and one or
940 more option letters. Move past the number. */
941 do ++a;
942 while (ISDIGIT (*a));
944 /* Pointer to the byte after the last digit. */
945 end_n_string = a;
947 /* Parse any appended option letters. */
948 for (; *a; a++)
950 switch (*a)
952 case 'c':
953 count_lines = false;
954 multiplier_char = 0;
955 break;
957 case 'b':
958 case 'k':
959 case 'm':
960 count_lines = false;
961 multiplier_char = *a;
962 break;
964 case 'l':
965 count_lines = true;
966 break;
968 case 'q':
969 header_mode = never;
970 break;
972 case 'v':
973 header_mode = always;
974 break;
976 default:
977 error (0, 0, _("invalid trailing option -- %c"), *a);
978 usage (EXIT_FAILURE);
982 /* Append the multiplier character (if any) onto the end of
983 the digit string. Then add NUL byte if necessary. */
984 *end_n_string = multiplier_char;
985 if (multiplier_char)
986 *(++end_n_string) = 0;
988 n_units = string_to_integer (count_lines, n_string);
990 /* Make the options we just parsed invisible to getopt. */
991 argv[1] = argv[0];
992 argv++;
993 argc--;
996 while ((c = getopt_long (argc, argv, "c:n:qv0123456789", long_options, NULL))
997 != -1)
999 switch (c)
1001 case PRESUME_INPUT_PIPE_OPTION:
1002 presume_input_pipe = true;
1003 break;
1005 case 'c':
1006 count_lines = false;
1007 elide_from_end = (*optarg == '-');
1008 if (elide_from_end)
1009 ++optarg;
1010 n_units = string_to_integer (count_lines, optarg);
1011 break;
1013 case 'n':
1014 count_lines = true;
1015 elide_from_end = (*optarg == '-');
1016 if (elide_from_end)
1017 ++optarg;
1018 n_units = string_to_integer (count_lines, optarg);
1019 break;
1021 case 'q':
1022 header_mode = never;
1023 break;
1025 case 'v':
1026 header_mode = always;
1027 break;
1029 case_GETOPT_HELP_CHAR;
1031 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
1033 default:
1034 if (ISDIGIT (c))
1035 error (0, 0, _("invalid trailing option -- %c"), c);
1036 usage (EXIT_FAILURE);
1040 if (header_mode == always
1041 || (header_mode == multiple_files && optind < argc - 1))
1042 print_headers = true;
1044 if ( ! count_lines && elide_from_end && OFF_T_MAX < n_units)
1046 char umax_buf[INT_BUFSIZE_BOUND (uintmax_t)];
1047 error (EXIT_FAILURE, 0, _("%s: number of bytes is too large"),
1048 umaxtostr (n_units, umax_buf));
1051 file_list = (optind < argc
1052 ? (char const *const *) &argv[optind]
1053 : default_file_list);
1055 if (O_BINARY && ! isatty (STDOUT_FILENO))
1056 xfreopen (NULL, "wb", stdout);
1058 for (i = 0; file_list[i]; ++i)
1059 ok &= head_file (file_list[i], n_units, count_lines, elide_from_end);
1061 if (have_read_stdin && close (STDIN_FILENO) < 0)
1062 error (EXIT_FAILURE, errno, "-");
1064 exit (ok ? EXIT_SUCCESS : EXIT_FAILURE);