1 /* head -- output first part of file(s)
2 Copyright (C) 1989-2024 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 <https://www.gnu.org/licenses/>. */
17 /* Options: (see usage)
18 Reads from standard input if no files are given or when a filename of
20 By default, filename headers are printed only if more than one file
22 By default, prints the first 10 lines (head -n 10).
24 David MacKenzie <djm@gnu.ai.mit.edu> */
30 #include <sys/types.h>
35 #include "full-read.h"
36 #include "safe-read.h"
37 #include "stat-size.h"
38 #include "xbinary-io.h"
39 #include "xdectoint.h"
41 /* The official name of this program (e.g., no 'g' prefix). */
42 #define PROGRAM_NAME "head"
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 /* Character to split lines by. */
63 /* When to print the filename banners. */
66 multiple_files
, always
, never
69 /* Have we ever read standard input? */
70 static bool have_read_stdin
;
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. */
83 PRESUME_INPUT_PIPE_OPTION
= CHAR_MAX
+ 1
86 static struct option
const long_options
[] =
88 {"bytes", required_argument
, nullptr, 'c'},
89 {"lines", required_argument
, nullptr, 'n'},
90 {"-presume-input-pipe", no_argument
, nullptr,
91 PRESUME_INPUT_PIPE_OPTION
}, /* do not document */
92 {"quiet", no_argument
, nullptr, 'q'},
93 {"silent", no_argument
, nullptr, 'q'},
94 {"verbose", no_argument
, nullptr, 'v'},
95 {"zero-terminated", no_argument
, nullptr, 'z'},
96 {GETOPT_HELP_OPTION_DECL
},
97 {GETOPT_VERSION_OPTION_DECL
},
98 {nullptr, 0, nullptr, 0}
104 if (status
!= EXIT_SUCCESS
)
109 Usage: %s [OPTION]... [FILE]...\n\
113 Print the first %d lines of each FILE to standard output.\n\
114 With more than one FILE, precede each with a header giving the file name.\n\
118 emit_mandatory_arg_note ();
121 -c, --bytes=[-]NUM print the first NUM bytes of each file;\n\
122 with the leading '-', print all but the last\n\
123 NUM bytes of each file\n\
124 -n, --lines=[-]NUM print the first NUM lines instead of the first %d;\n\
125 with the leading '-', print all but the last\n\
126 NUM lines of each file\n\
129 -q, --quiet, --silent never print headers giving file names\n\
130 -v, --verbose always print headers giving file names\n\
133 -z, --zero-terminated line delimiter is NUL, not newline\n\
135 fputs (HELP_OPTION_DESCRIPTION
, stdout
);
136 fputs (VERSION_OPTION_DESCRIPTION
, stdout
);
139 NUM may have a multiplier suffix:\n\
140 b 512, kB 1000, K 1024, MB 1000*1000, M 1024*1024,\n\
141 GB 1000*1000*1000, G 1024*1024*1024, and so on for T, P, E, Z, Y, R, Q.\n\
142 Binary prefixes can be used, too: KiB=K, MiB=M, and so on.\n\
144 emit_ancillary_info (PROGRAM_NAME
);
150 diagnose_copy_fd_failure (enum Copy_fd_status err
, char const *filename
)
154 case COPY_FD_READ_ERROR
:
155 error (0, errno
, _("error reading %s"), quoteaf (filename
));
157 case COPY_FD_UNEXPECTED_EOF
:
158 error (0, errno
, _("%s: file has shrunk too much"), quotef (filename
));
166 write_header (char const *filename
)
168 static bool first_file
= true;
170 printf ("%s==> %s <==\n", (first_file
? "" : "\n"), filename
);
174 /* Write N_BYTES from BUFFER to stdout.
175 Exit immediately on error with a single diagnostic. */
178 xwrite_stdout (char const *buffer
, size_t n_bytes
)
180 if (n_bytes
> 0 && fwrite (buffer
, 1, n_bytes
, stdout
) < n_bytes
)
182 clearerr (stdout
); /* To avoid redundant close_stdout diagnostic. */
184 error (EXIT_FAILURE
, errno
, _("error writing %s"),
185 quoteaf ("standard output"));
189 /* Copy no more than N_BYTES from file descriptor SRC_FD to stdout.
190 Return an appropriate indication of success or read failure. */
192 static enum Copy_fd_status
193 copy_fd (int src_fd
, uintmax_t n_bytes
)
197 /* Copy the file contents. */
200 idx_t n_to_read
= MIN (n_bytes
, sizeof buf
);
201 ptrdiff_t n_read
= safe_read (src_fd
, buf
, n_to_read
);
203 return COPY_FD_READ_ERROR
;
207 if (n_read
== 0 && n_bytes
!= 0)
208 return COPY_FD_UNEXPECTED_EOF
;
210 xwrite_stdout (buf
, n_read
);
216 /* Call lseek (FD, OFFSET, WHENCE), where file descriptor FD
217 corresponds to the file FILENAME. WHENCE must be SEEK_SET or
218 SEEK_CUR. Return the resulting offset. Give a diagnostic and
219 return -1 if lseek fails. */
222 elseek (int fd
, off_t offset
, int whence
, char const *filename
)
224 off_t new_offset
= lseek (fd
, offset
, whence
);
229 ? N_("%s: cannot seek to offset %jd")
230 : N_("%s: cannot seek to relative offset %jd")),
237 /* For an input file with name FILENAME and descriptor FD,
238 output all but the last N_ELIDE bytes.
239 If CURRENT_POS is nonnegative, assume that the input file is
240 positioned at CURRENT_POS and that it should be repositioned to
241 just before the elided bytes before returning.
242 Return true upon success.
243 Give a diagnostic and return false upon error. */
245 elide_tail_bytes_pipe (char const *filename
, int fd
, uintmax_t n_elide
,
248 uintmax_t desired_pos
= current_pos
;
251 #ifndef HEAD_TAIL_PIPE_READ_BUFSIZE
252 # define HEAD_TAIL_PIPE_READ_BUFSIZE BUFSIZ
254 #define READ_BUFSIZE HEAD_TAIL_PIPE_READ_BUFSIZE
256 /* If we're eliding no more than this many bytes, then it's ok to allocate
257 more memory in order to use a more time-efficient algorithm.
258 FIXME: use a fraction of available memory instead, as in sort.
259 FIXME: is this even worthwhile? */
260 #ifndef HEAD_TAIL_PIPE_BYTECOUNT_THRESHOLD
261 # define HEAD_TAIL_PIPE_BYTECOUNT_THRESHOLD 1024 * 1024
264 #if HEAD_TAIL_PIPE_BYTECOUNT_THRESHOLD < 2 * READ_BUFSIZE
265 # error "HEAD_TAIL_PIPE_BYTECOUNT_THRESHOLD must be at least 2 * READ_BUFSIZE"
268 /* Two cases to consider...
269 1) n_elide is small enough that we can afford to double-buffer:
270 allocate 2 * (READ_BUFSIZE + n_elide) bytes
271 2) n_elide is too big for that, so we allocate only
272 (READ_BUFSIZE + n_elide) bytes
274 FIXME: profile, to see if double-buffering is worthwhile
276 CAUTION: do not fail (out of memory) when asked to elide
277 a ridiculous amount, but when given only a small input. */
279 static_assert (READ_BUFSIZE
<= IDX_MAX
);
280 static_assert (HEAD_TAIL_PIPE_BYTECOUNT_THRESHOLD
<= IDX_MAX
- READ_BUFSIZE
);
281 if (n_elide
<= HEAD_TAIL_PIPE_BYTECOUNT_THRESHOLD
)
283 idx_t in_elide
= n_elide
;
286 idx_t n_to_read
= READ_BUFSIZE
+ n_elide
;
289 b
[0] = xnmalloc (2, n_to_read
);
290 b
[1] = b
[0] + n_to_read
;
292 for (i
= false; ! eof
; i
= !i
)
294 idx_t n_read
= full_read (fd
, b
[i
], n_to_read
);
296 if (n_read
< n_to_read
)
300 error (0, errno
, _("error reading %s"), quoteaf (filename
));
306 if (n_read
<= in_elide
)
310 /* The input is no larger than the number of bytes
311 to elide. So there's nothing to output, and
316 delta
= in_elide
- n_read
;
322 /* Output any (but maybe just part of the) elided data from
323 the previous round. */
326 desired_pos
+= in_elide
- delta
;
327 xwrite_stdout (b
[!i
] + READ_BUFSIZE
, in_elide
- delta
);
331 if (in_elide
< n_read
)
333 desired_pos
+= n_read
- in_elide
;
334 xwrite_stdout (b
[i
], n_read
- in_elide
);
342 /* Read blocks of size READ_BUFSIZE, until we've read at least n_elide
343 bytes. Then, for each new buffer we read, also write an old one. */
349 idx_t remainder
= n_elide
% READ_BUFSIZE
;
350 /* The number of buffers needed to hold n_elide bytes plus one
351 extra buffer. They are allocated lazily, so don't report
352 overflow now simply because the number does not fit into idx_t. */
353 uintmax_t n_bufs
= n_elide
/ READ_BUFSIZE
+ (remainder
!= 0) + 1;
355 idx_t n_array_alloc
= 0;
357 bool buffered_enough
= false;
359 for (i
= 0, i_next
= 1; !eof
; i
= i_next
, i_next
= (i_next
+ 1) % n_bufs
)
361 if (n_array_alloc
== i
)
362 b
= xpalloc (b
, &n_array_alloc
, 1, MIN (n_bufs
, PTRDIFF_MAX
),
365 if (! buffered_enough
)
367 b
[i
] = xmalloc (READ_BUFSIZE
);
370 n_read
= full_read (fd
, b
[i
], READ_BUFSIZE
);
371 if (n_read
< READ_BUFSIZE
)
375 error (0, errno
, _("error reading %s"), quoteaf (filename
));
383 buffered_enough
= true;
387 desired_pos
+= n_read
;
388 xwrite_stdout (b
[i_next
], n_read
);
392 /* Output the remainder: rem bytes from b[i] + n_read. */
393 idx_t rem
= READ_BUFSIZE
- remainder
;
396 idx_t n_bytes_left_in_b_i
= READ_BUFSIZE
- n_read
;
398 if (rem
< n_bytes_left_in_b_i
)
400 xwrite_stdout (b
[i
] + n_read
, rem
);
404 xwrite_stdout (b
[i
] + n_read
, n_bytes_left_in_b_i
);
405 xwrite_stdout (b
[i_next
], rem
- n_bytes_left_in_b_i
);
408 else if (i
+ 1 == n_bufs
)
411 n_elide < file_size < (n_bufs - 1) * READ_BUFSIZE.
415 |---------!---------!---------!---------|
416 |---- n_elide----------|
419 |---- file size -----------|
421 |(n_bufs - 1) * READ_BUFSIZE--|
423 idx_t y
= READ_BUFSIZE
- rem
;
424 idx_t x
= n_read
- y
;
426 xwrite_stdout (b
[i_next
], x
);
430 for (i
= 0; i
< n_alloc
; i
++)
435 if (0 <= current_pos
&& elseek (fd
, desired_pos
, SEEK_SET
, filename
) < 0)
440 /* For the file FILENAME with descriptor FD, output all but the last N_ELIDE
441 bytes. If SIZE is nonnegative, this is a regular file positioned
442 at CURRENT_POS with SIZE bytes. Return true on success.
443 Give a diagnostic and return false upon error. */
445 /* NOTE: if the input file shrinks by more than N_ELIDE bytes between
446 the length determination and the actual reading, then head fails. */
449 elide_tail_bytes_file (char const *filename
, int fd
, uintmax_t n_elide
,
450 struct stat
const *st
, off_t current_pos
)
452 off_t size
= st
->st_size
;
453 if (presume_input_pipe
|| current_pos
< 0 || size
<= STP_BLKSIZE (st
))
454 return elide_tail_bytes_pipe (filename
, fd
, n_elide
, current_pos
);
457 /* Be careful here. The current position may actually be
458 beyond the end of the file. */
459 off_t diff
= size
- current_pos
;
460 off_t bytes_remaining
= diff
< 0 ? 0 : diff
;
462 if (bytes_remaining
<= n_elide
)
465 enum Copy_fd_status err
= copy_fd (fd
, bytes_remaining
- n_elide
);
466 if (err
== COPY_FD_OK
)
469 diagnose_copy_fd_failure (err
, filename
);
474 /* For an input file with name FILENAME and descriptor FD,
475 output all but the last N_ELIDE bytes.
476 If CURRENT_POS is nonnegative, the input file is positioned there
477 and should be repositioned to just before the elided bytes.
478 Buffer the specified number of lines as a linked list of LBUFFERs,
479 adding them as needed. Return true if successful. */
482 elide_tail_lines_pipe (char const *filename
, int fd
, uintmax_t n_elide
,
487 char buffer
[BUFSIZ
+ 1];
490 struct linebuffer
*next
;
492 off_t desired_pos
= current_pos
;
493 typedef struct linebuffer LBUFFER
;
494 LBUFFER
*first
, *last
, *tmp
;
495 size_t total_lines
= 0; /* Total number of newlines in all buffers. */
497 ptrdiff_t n_read
; /* Size in bytes of most recent read */
499 first
= last
= xmalloc (sizeof (LBUFFER
));
500 first
->nbytes
= first
->nlines
= 0;
501 first
->next
= nullptr;
502 tmp
= xmalloc (sizeof (LBUFFER
));
504 /* Always read into a fresh buffer.
505 Read, (producing no output) until we've accumulated at least
506 n_elide newlines, or until EOF, whichever comes first. */
509 n_read
= safe_read (fd
, tmp
->buffer
, BUFSIZ
);
515 desired_pos
+= n_read
;
516 xwrite_stdout (tmp
->buffer
, n_read
);
520 tmp
->nbytes
= n_read
;
524 /* Count the number of newlines just read. */
526 char *buffer_end
= tmp
->buffer
+ n_read
;
527 *buffer_end
= line_end
;
528 char const *p
= tmp
->buffer
;
529 while ((p
= rawmemchr (p
, line_end
)) < buffer_end
)
535 total_lines
+= tmp
->nlines
;
537 /* If there is enough room in the last buffer read, just append the new
538 one to it. This is because when reading from a pipe, 'n_read' can
539 often be very small. */
540 if (tmp
->nbytes
+ last
->nbytes
< BUFSIZ
)
542 memcpy (&last
->buffer
[last
->nbytes
], tmp
->buffer
, tmp
->nbytes
);
543 last
->nbytes
+= tmp
->nbytes
;
544 last
->nlines
+= tmp
->nlines
;
548 /* If there's not enough room, link the new buffer onto the end of
549 the list, then either free up the oldest buffer for the next
550 read if that would leave enough lines, or else malloc a new one.
551 Some compaction mechanism is possible but probably not
553 last
= last
->next
= tmp
;
554 if (n_elide
< total_lines
- first
->nlines
)
556 desired_pos
+= first
->nbytes
;
557 xwrite_stdout (first
->buffer
, first
->nbytes
);
559 total_lines
-= first
->nlines
;
563 tmp
= xmalloc (sizeof (LBUFFER
));
571 error (0, errno
, _("error reading %s"), quoteaf (filename
));
576 /* If we read any bytes at all, count the incomplete line
577 on files that don't end with a newline. */
578 if (last
->nbytes
&& last
->buffer
[last
->nbytes
- 1] != line_end
)
584 for (tmp
= first
; n_elide
< total_lines
- tmp
->nlines
; tmp
= tmp
->next
)
586 desired_pos
+= tmp
->nbytes
;
587 xwrite_stdout (tmp
->buffer
, tmp
->nbytes
);
588 total_lines
-= tmp
->nlines
;
591 /* Print the first 'total_lines - n_elide' lines of tmp->buffer. */
592 if (n_elide
< total_lines
)
594 size_t n
= total_lines
- n_elide
;
595 char const *buffer_end
= tmp
->buffer
+ tmp
->nbytes
;
596 char const *p
= tmp
->buffer
;
597 while (n
&& (p
= memchr (p
, line_end
, buffer_end
- p
)))
603 desired_pos
+= p
- tmp
->buffer
;
604 xwrite_stdout (tmp
->buffer
, p
- tmp
->buffer
);
615 if (0 <= current_pos
&& elseek (fd
, desired_pos
, SEEK_SET
, filename
) < 0)
620 /* Output all but the last N_LINES lines of the input stream defined by
621 FD, START_POS, and SIZE.
622 START_POS is the starting position of the read pointer for the file
623 associated with FD (may be nonzero).
624 SIZE is the file size in bytes.
625 Return true upon success.
626 Give a diagnostic and return false upon error.
628 NOTE: this code is very similar to that of tail.c's file_lines function.
629 Unfortunately, factoring out some common core looks like it'd result
630 in a less efficient implementation or a messy interface. */
632 elide_tail_lines_seekable (char const *pretty_filename
, int fd
,
634 off_t start_pos
, off_t size
)
637 ptrdiff_t bytes_read
;
640 /* Set 'bytes_read' to the size of the last, probably partial, buffer;
641 0 < 'bytes_read' <= 'BUFSIZ'. */
642 bytes_read
= (pos
- start_pos
) % BUFSIZ
;
645 /* Make 'pos' a multiple of 'BUFSIZ' (0 if the file is short), so that all
646 reads will be on block boundaries, which might increase efficiency. */
648 if (elseek (fd
, pos
, SEEK_SET
, pretty_filename
) < 0)
650 bytes_read
= safe_read (fd
, buffer
, bytes_read
);
653 error (0, errno
, _("error reading %s"), quoteaf (pretty_filename
));
657 /* n_lines == 0 case needs special treatment. */
658 const bool all_lines
= !n_lines
;
660 /* Count the incomplete line on files that don't end with a newline. */
661 if (n_lines
&& bytes_read
&& buffer
[bytes_read
- 1] != line_end
)
666 /* Scan backward, counting the newlines in this bufferfull. */
668 idx_t n
= bytes_read
;
676 nl
= memrchr (buffer
, line_end
, n
);
684 /* If necessary, restore the file pointer and copy
685 input to output up to position, POS. */
688 enum Copy_fd_status err
;
689 if (elseek (fd
, start_pos
, SEEK_SET
, pretty_filename
) < 0)
692 err
= copy_fd (fd
, pos
- start_pos
);
693 if (err
!= COPY_FD_OK
)
695 diagnose_copy_fd_failure (err
, pretty_filename
);
700 /* Output the initial portion of the buffer
701 in which we found the desired newline byte. */
702 xwrite_stdout (buffer
, n
+ 1);
704 /* Set file pointer to the byte after what we've output. */
705 return 0 <= elseek (fd
, pos
+ n
+ 1, SEEK_SET
, pretty_filename
);
709 /* Not enough newlines in that bufferfull. */
710 if (pos
== start_pos
)
712 /* Not enough lines in the file. */
716 if (elseek (fd
, pos
, SEEK_SET
, pretty_filename
) < 0)
719 bytes_read
= safe_read (fd
, buffer
, BUFSIZ
);
722 error (0, errno
, _("error reading %s"), quoteaf (pretty_filename
));
726 /* FIXME: is this dead code?
727 Consider the test, pos == start_pos, above. */
733 /* For the file FILENAME with descriptor FD, output all but the last N_ELIDE
734 lines. If SIZE is nonnegative, this is a regular file positioned
735 at START_POS with SIZE bytes. Return true on success.
736 Give a diagnostic and return nonzero upon error. */
739 elide_tail_lines_file (char const *filename
, int fd
, uintmax_t n_elide
,
740 struct stat
const *st
, off_t current_pos
)
742 off_t size
= st
->st_size
;
743 if (presume_input_pipe
|| current_pos
< 0 || size
<= STP_BLKSIZE (st
))
744 return elide_tail_lines_pipe (filename
, fd
, n_elide
, current_pos
);
747 /* Find the offset, OFF, of the Nth newline from the end,
748 but not counting the last byte of the file.
749 If found, write from current position to OFF, inclusive.
750 Otherwise, just return true. */
752 return (size
<= current_pos
753 || elide_tail_lines_seekable (filename
, fd
, n_elide
,
759 head_bytes (char const *filename
, int fd
, uintmax_t bytes_to_write
)
762 size_t bytes_to_read
= BUFSIZ
;
764 while (bytes_to_write
)
766 if (bytes_to_write
< bytes_to_read
)
767 bytes_to_read
= bytes_to_write
;
768 ptrdiff_t bytes_read
= safe_read (fd
, buffer
, bytes_to_read
);
771 error (0, errno
, _("error reading %s"), quoteaf (filename
));
776 xwrite_stdout (buffer
, bytes_read
);
777 bytes_to_write
-= bytes_read
;
783 head_lines (char const *filename
, int fd
, uintmax_t lines_to_write
)
787 while (lines_to_write
)
789 ptrdiff_t bytes_read
= safe_read (fd
, buffer
, BUFSIZ
);
790 idx_t bytes_to_write
= 0;
794 error (0, errno
, _("error reading %s"), quoteaf (filename
));
799 while (bytes_to_write
< bytes_read
)
800 if (buffer
[bytes_to_write
++] == line_end
&& --lines_to_write
== 0)
802 off_t n_bytes_past_EOL
= bytes_read
- bytes_to_write
;
803 /* If we have read more data than that on the specified number
804 of lines, try to seek back to the position we would have
805 gotten to had we been reading one byte at a time. */
806 if (lseek (fd
, -n_bytes_past_EOL
, SEEK_CUR
) < 0)
809 if (fstat (fd
, &st
) != 0 || S_ISREG (st
.st_mode
))
810 elseek (fd
, -n_bytes_past_EOL
, SEEK_CUR
, filename
);
814 xwrite_stdout (buffer
, bytes_to_write
);
820 head (char const *filename
, int fd
, uintmax_t n_units
, bool count_lines
,
824 write_header (filename
);
828 /* Optimize for "infinite" elisions. */
829 if (n_units
== UINTMAX_MAX
)
832 off_t current_pos
= -1;
834 if (fstat (fd
, &st
) != 0)
836 error (0, errno
, _("cannot fstat %s"),
840 if (! presume_input_pipe
&& usable_st_size (&st
))
842 current_pos
= elseek (fd
, 0, SEEK_CUR
, filename
);
847 return elide_tail_lines_file (filename
, fd
, n_units
, &st
, current_pos
);
849 return elide_tail_bytes_file (filename
, fd
, n_units
, &st
, current_pos
);
852 return head_lines (filename
, fd
, n_units
);
854 return head_bytes (filename
, fd
, n_units
);
858 head_file (char const *filename
, uintmax_t n_units
, bool count_lines
,
863 bool is_stdin
= STREQ (filename
, "-");
867 have_read_stdin
= true;
869 filename
= _("standard input");
870 xset_binary_mode (STDIN_FILENO
, O_BINARY
);
874 fd
= open (filename
, O_RDONLY
| O_BINARY
);
877 error (0, errno
, _("cannot open %s for reading"), quoteaf (filename
));
882 ok
= head (filename
, fd
, n_units
, count_lines
, elide_from_end
);
883 if (!is_stdin
&& close (fd
) != 0)
885 error (0, errno
, _("failed to close %s"), quoteaf (filename
));
891 /* Convert a string of decimal digits, N_STRING, with an optional suffix
892 to an integral value. Upon successful conversion,
893 return that value. If it cannot be converted, give a diagnostic and exit.
894 If it is too large, silently return UINTMAX_MAX.
895 COUNT_LINES indicates whether N_STRING is a number of bytes or a number
896 of lines. It is used solely to give a more specific diagnostic. */
899 string_to_integer (bool count_lines
, char const *n_string
)
901 return xnumtoumax (n_string
, 10, 0, UINTMAX_MAX
, "bkKmMGTPEZYRQ0",
903 ? _("invalid number of lines")
904 : _("invalid number of bytes")),
905 0, XTOINT_MAX_QUIET
);
909 main (int argc
, char **argv
)
911 enum header_mode header_mode
= multiple_files
;
916 /* Number of items to output, or to elide from the end.
917 UINTMAX_MAX stands for an essentially unlimited number. */
918 uintmax_t n_units
= DEFAULT_NUMBER
;
920 /* If true, interpret the numeric argument as the number of lines.
921 Otherwise, interpret it as the number of bytes. */
922 bool count_lines
= true;
924 /* Elide the specified number of lines or bytes, counting from
925 the end of the file. */
926 bool elide_from_end
= false;
928 /* Initializer for file_list if no file-arguments
929 were specified on the command line. */
930 static char const *const default_file_list
[] = {"-", nullptr};
931 char const *const *file_list
;
933 initialize_main (&argc
, &argv
);
934 set_program_name (argv
[0]);
935 setlocale (LC_ALL
, "");
936 bindtextdomain (PACKAGE
, LOCALEDIR
);
937 textdomain (PACKAGE
);
939 atexit (close_stdout
);
941 have_read_stdin
= false;
943 print_headers
= false;
947 if (1 < argc
&& argv
[1][0] == '-' && ISDIGIT (argv
[1][1]))
950 char *n_string
= ++a
;
952 char multiplier_char
= 0;
954 /* Old option syntax; a dash, one or more digits, and one or
955 more option letters. Move past the number. */
957 while (ISDIGIT (*a
));
959 /* Pointer to the byte after the last digit. */
962 /* Parse any appended option letters. */
976 multiplier_char
= *a
;
988 header_mode
= always
;
996 error (0, 0, _("invalid trailing option -- %c"), *a
);
997 usage (EXIT_FAILURE
);
1001 /* Append the multiplier character (if any) onto the end of
1002 the digit string. Then add NUL byte if necessary. */
1003 *end_n_string
= multiplier_char
;
1004 if (multiplier_char
)
1005 *(++end_n_string
) = 0;
1007 n_units
= string_to_integer (count_lines
, n_string
);
1009 /* Make the options we just parsed invisible to getopt. */
1015 while ((c
= getopt_long (argc
, argv
, "c:n:qvz0123456789",
1016 long_options
, nullptr))
1021 case PRESUME_INPUT_PIPE_OPTION
:
1022 presume_input_pipe
= true;
1026 count_lines
= false;
1027 elide_from_end
= (*optarg
== '-');
1030 n_units
= string_to_integer (count_lines
, optarg
);
1035 elide_from_end
= (*optarg
== '-');
1038 n_units
= string_to_integer (count_lines
, optarg
);
1042 header_mode
= never
;
1046 header_mode
= always
;
1053 case_GETOPT_HELP_CHAR
;
1055 case_GETOPT_VERSION_CHAR (PROGRAM_NAME
, AUTHORS
);
1059 error (0, 0, _("invalid trailing option -- %c"), c
);
1060 usage (EXIT_FAILURE
);
1064 if (header_mode
== always
1065 || (header_mode
== multiple_files
&& optind
< argc
- 1))
1066 print_headers
= true;
1068 file_list
= (optind
< argc
1069 ? (char const *const *) &argv
[optind
]
1070 : default_file_list
);
1072 xset_binary_mode (STDOUT_FILENO
, O_BINARY
);
1074 for (i
= 0; file_list
[i
]; ++i
)
1075 ok
&= head_file (file_list
[i
], n_units
, count_lines
, elide_from_end
);
1077 if (have_read_stdin
&& close (STDIN_FILENO
) < 0)
1078 error (EXIT_FAILURE
, errno
, "-");
1080 return ok
? EXIT_SUCCESS
: EXIT_FAILURE
;