1 /* head -- output first part of file(s)
2 Copyright (C) 1989-2016 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
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"
37 #include "safe-read.h"
38 #include "stat-size.h"
40 #include "xdectoint.h"
42 /* The official name of this program (e.g., no 'g' prefix). */
43 #define PROGRAM_NAME "head"
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 /* Character to split lines by. */
64 /* When to print the filename banners. */
67 multiple_files
, always
, never
70 /* Have we ever read standard input? */
71 static bool have_read_stdin
;
77 COPY_FD_UNEXPECTED_EOF
80 /* For long options that have no equivalent short option, use a
81 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
84 PRESUME_INPUT_PIPE_OPTION
= CHAR_MAX
+ 1
87 static struct option
const long_options
[] =
89 {"bytes", required_argument
, NULL
, 'c'},
90 {"lines", required_argument
, NULL
, 'n'},
91 {"-presume-input-pipe", no_argument
, NULL
,
92 PRESUME_INPUT_PIPE_OPTION
}, /* do not document */
93 {"quiet", no_argument
, NULL
, 'q'},
94 {"silent", no_argument
, NULL
, 'q'},
95 {"verbose", no_argument
, NULL
, 'v'},
96 {"zero-terminated", no_argument
, NULL
, 'z'},
97 {GETOPT_HELP_OPTION_DECL
},
98 {GETOPT_VERSION_OPTION_DECL
},
105 if (status
!= EXIT_SUCCESS
)
110 Usage: %s [OPTION]... [FILE]...\n\
114 Print the first %d lines of each FILE to standard output.\n\
115 With more than one FILE, precede each with a header giving the file name.\n\
119 emit_mandatory_arg_note ();
122 -c, --bytes=[-]NUM print the first NUM bytes of each file;\n\
123 with the leading '-', print all but the last\n\
124 NUM bytes of each file\n\
125 -n, --lines=[-]NUM print the first NUM lines instead of the first %d;\n\
126 with the leading '-', print all but the last\n\
127 NUM lines of each file\n\
130 -q, --quiet, --silent never print headers giving file names\n\
131 -v, --verbose always print headers giving file names\n\
134 -z, --zero-terminated line delimiter is NUL, not newline\n\
136 fputs (HELP_OPTION_DESCRIPTION
, stdout
);
137 fputs (VERSION_OPTION_DESCRIPTION
, stdout
);
140 NUM may have a multiplier suffix:\n\
141 b 512, kB 1000, K 1024, MB 1000*1000, M 1024*1024,\n\
142 GB 1000*1000*1000, G 1024*1024*1024, and so on for T, P, E, Z, Y.\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 (const char *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. */
183 error (EXIT_FAILURE
, errno
, _("error writing %s"),
184 quoteaf ("standard output"));
188 /* Copy no more than N_BYTES from file descriptor SRC_FD to stdout.
189 Return an appropriate indication of success or read failure. */
191 static enum Copy_fd_status
192 copy_fd (int src_fd
, uintmax_t n_bytes
)
195 const size_t buf_size
= sizeof (buf
);
197 /* Copy the file contents. */
200 size_t n_to_read
= MIN (buf_size
, n_bytes
);
201 size_t n_read
= safe_read (src_fd
, buf
, n_to_read
);
202 if (n_read
== SAFE_READ_ERROR
)
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
);
225 char buf
[INT_BUFSIZE_BOUND (offset
)];
230 ? N_("%s: cannot seek to offset %s")
231 : N_("%s: cannot seek to relative offset %s")),
233 offtostr (offset
, buf
));
238 /* For an input file with name FILENAME and descriptor FD,
239 output all but the last N_ELIDE_0 bytes.
240 If CURRENT_POS is nonnegative, assume that the input file is
241 positioned at CURRENT_POS and that it should be repositioned to
242 just before the elided bytes before returning.
243 Return true upon success.
244 Give a diagnostic and return false upon error. */
246 elide_tail_bytes_pipe (const char *filename
, int fd
, uintmax_t n_elide_0
,
249 size_t n_elide
= n_elide_0
;
250 uintmax_t desired_pos
= current_pos
;
253 #ifndef HEAD_TAIL_PIPE_READ_BUFSIZE
254 # define HEAD_TAIL_PIPE_READ_BUFSIZE BUFSIZ
256 #define READ_BUFSIZE HEAD_TAIL_PIPE_READ_BUFSIZE
258 /* If we're eliding no more than this many bytes, then it's ok to allocate
259 more memory in order to use a more time-efficient algorithm.
260 FIXME: use a fraction of available memory instead, as in sort.
261 FIXME: is this even worthwhile? */
262 #ifndef HEAD_TAIL_PIPE_BYTECOUNT_THRESHOLD
263 # define HEAD_TAIL_PIPE_BYTECOUNT_THRESHOLD 1024 * 1024
266 #if HEAD_TAIL_PIPE_BYTECOUNT_THRESHOLD < 2 * READ_BUFSIZE
267 "HEAD_TAIL_PIPE_BYTECOUNT_THRESHOLD must be at least 2 * READ_BUFSIZE"
270 if (SIZE_MAX
< n_elide_0
+ READ_BUFSIZE
)
272 char umax_buf
[INT_BUFSIZE_BOUND (n_elide_0
)];
273 error (EXIT_FAILURE
, 0, _("%s: number of bytes is too large"),
274 umaxtostr (n_elide_0
, umax_buf
));
277 /* Two cases to consider...
278 1) n_elide is small enough that we can afford to double-buffer:
279 allocate 2 * (READ_BUFSIZE + n_elide) bytes
280 2) n_elide is too big for that, so we allocate only
281 (READ_BUFSIZE + n_elide) bytes
283 FIXME: profile, to see if double-buffering is worthwhile
285 CAUTION: do not fail (out of memory) when asked to elide
286 a ridiculous amount, but when given only a small input. */
288 if (n_elide
<= HEAD_TAIL_PIPE_BYTECOUNT_THRESHOLD
)
292 size_t n_to_read
= READ_BUFSIZE
+ n_elide
;
295 b
[0] = xnmalloc (2, n_to_read
);
296 b
[1] = b
[0] + n_to_read
;
298 for (i
= false; ! eof
; i
= !i
)
300 size_t n_read
= full_read (fd
, b
[i
], n_to_read
);
302 if (n_read
< n_to_read
)
306 error (0, errno
, _("error reading %s"), quoteaf (filename
));
312 if (n_read
<= n_elide
)
316 /* The input is no larger than the number of bytes
317 to elide. So there's nothing to output, and
322 delta
= n_elide
- n_read
;
328 /* Output any (but maybe just part of the) elided data from
329 the previous round. */
332 desired_pos
+= n_elide
- delta
;
333 xwrite_stdout (b
[!i
] + READ_BUFSIZE
, n_elide
- delta
);
337 if (n_elide
< n_read
)
339 desired_pos
+= n_read
- n_elide
;
340 xwrite_stdout (b
[i
], n_read
- n_elide
);
348 /* Read blocks of size READ_BUFSIZE, until we've read at least n_elide
349 bytes. Then, for each new buffer we read, also write an old one. */
353 bool buffered_enough
;
356 /* Round n_elide up to a multiple of READ_BUFSIZE. */
357 size_t rem
= READ_BUFSIZE
- (n_elide
% READ_BUFSIZE
);
358 size_t n_elide_round
= n_elide
+ rem
;
359 size_t n_bufs
= n_elide_round
/ READ_BUFSIZE
+ 1;
361 size_t n_array_alloc
= 0;
363 buffered_enough
= false;
364 for (i
= 0, i_next
= 1; !eof
; i
= i_next
, i_next
= (i_next
+ 1) % n_bufs
)
366 if (n_array_alloc
== i
)
368 /* reallocate between 16 and n_bufs entries. */
369 if (n_array_alloc
== 0)
370 n_array_alloc
= MIN (n_bufs
, 16);
371 else if (n_array_alloc
<= n_bufs
/ 2)
374 n_array_alloc
= n_bufs
;
375 b
= xnrealloc (b
, n_array_alloc
, sizeof *b
);
378 if (! buffered_enough
)
380 b
[i
] = xmalloc (READ_BUFSIZE
);
383 n_read
= full_read (fd
, b
[i
], READ_BUFSIZE
);
384 if (n_read
< READ_BUFSIZE
)
388 error (0, errno
, _("error reading %s"), quoteaf (filename
));
396 buffered_enough
= true;
400 desired_pos
+= n_read
;
401 xwrite_stdout (b
[i_next
], n_read
);
405 /* Output any remainder: rem bytes from b[i] + n_read. */
410 size_t n_bytes_left_in_b_i
= READ_BUFSIZE
- n_read
;
412 if (rem
< n_bytes_left_in_b_i
)
414 xwrite_stdout (b
[i
] + n_read
, rem
);
418 xwrite_stdout (b
[i
] + n_read
, n_bytes_left_in_b_i
);
419 xwrite_stdout (b
[i_next
], rem
- n_bytes_left_in_b_i
);
422 else if (i
+ 1 == n_bufs
)
424 /* This happens when n_elide < file_size < n_elide_round.
428 |---------!---------!---------!---------|
429 |---- n_elide ---------|
432 |---- file size -----------|
434 |---- n_elide_round ----------|
436 size_t y
= READ_BUFSIZE
- rem
;
437 size_t x
= n_read
- y
;
439 xwrite_stdout (b
[i_next
], x
);
444 for (i
= 0; i
< n_alloc
; i
++)
449 if (0 <= current_pos
&& elseek (fd
, desired_pos
, SEEK_SET
, filename
) < 0)
454 /* For the file FILENAME with descriptor FD, output all but the last N_ELIDE
455 bytes. If SIZE is nonnegative, this is a regular file positioned
456 at CURRENT_POS with SIZE bytes. Return true on success.
457 Give a diagnostic and return false upon error. */
459 /* NOTE: if the input file shrinks by more than N_ELIDE bytes between
460 the length determination and the actual reading, then head fails. */
463 elide_tail_bytes_file (const char *filename
, int fd
, uintmax_t n_elide
,
464 struct stat
const *st
, off_t current_pos
)
466 off_t size
= st
->st_size
;
467 if (presume_input_pipe
|| size
<= ST_BLKSIZE (*st
))
468 return elide_tail_bytes_pipe (filename
, fd
, n_elide
, current_pos
);
471 /* Be careful here. The current position may actually be
472 beyond the end of the file. */
473 off_t diff
= size
- current_pos
;
474 off_t bytes_remaining
= diff
< 0 ? 0 : diff
;
476 if (bytes_remaining
<= n_elide
)
479 enum Copy_fd_status err
= copy_fd (fd
, bytes_remaining
- n_elide
);
480 if (err
== COPY_FD_OK
)
483 diagnose_copy_fd_failure (err
, filename
);
488 /* For an input file with name FILENAME and descriptor FD,
489 output all but the last N_ELIDE_0 bytes.
490 If CURRENT_POS is nonnegative, the input file is positioned there
491 and should be repositioned to just before the elided bytes.
492 Buffer the specified number of lines as a linked list of LBUFFERs,
493 adding them as needed. Return true if successful. */
496 elide_tail_lines_pipe (const char *filename
, int fd
, uintmax_t n_elide
,
504 struct linebuffer
*next
;
506 uintmax_t desired_pos
= current_pos
;
507 typedef struct linebuffer LBUFFER
;
508 LBUFFER
*first
, *last
, *tmp
;
509 size_t total_lines
= 0; /* Total number of newlines in all buffers. */
511 size_t n_read
; /* Size in bytes of most recent read */
513 first
= last
= xmalloc (sizeof (LBUFFER
));
514 first
->nbytes
= first
->nlines
= 0;
516 tmp
= xmalloc (sizeof (LBUFFER
));
518 /* Always read into a fresh buffer.
519 Read, (producing no output) until we've accumulated at least
520 n_elide newlines, or until EOF, whichever comes first. */
523 n_read
= safe_read (fd
, tmp
->buffer
, BUFSIZ
);
524 if (n_read
== 0 || n_read
== SAFE_READ_ERROR
)
529 desired_pos
+= n_read
;
530 xwrite_stdout (tmp
->buffer
, n_read
);
534 tmp
->nbytes
= n_read
;
538 /* Count the number of newlines just read. */
540 char const *buffer_end
= tmp
->buffer
+ n_read
;
541 char const *p
= tmp
->buffer
;
542 while ((p
= memchr (p
, line_end
, buffer_end
- p
)))
548 total_lines
+= tmp
->nlines
;
550 /* If there is enough room in the last buffer read, just append the new
551 one to it. This is because when reading from a pipe, 'n_read' can
552 often be very small. */
553 if (tmp
->nbytes
+ last
->nbytes
< BUFSIZ
)
555 memcpy (&last
->buffer
[last
->nbytes
], tmp
->buffer
, tmp
->nbytes
);
556 last
->nbytes
+= tmp
->nbytes
;
557 last
->nlines
+= tmp
->nlines
;
561 /* If there's not enough room, link the new buffer onto the end of
562 the list, then either free up the oldest buffer for the next
563 read if that would leave enough lines, or else malloc a new one.
564 Some compaction mechanism is possible but probably not
566 last
= last
->next
= tmp
;
567 if (n_elide
< total_lines
- first
->nlines
)
569 desired_pos
+= first
->nbytes
;
570 xwrite_stdout (first
->buffer
, first
->nbytes
);
572 total_lines
-= first
->nlines
;
576 tmp
= xmalloc (sizeof (LBUFFER
));
582 if (n_read
== SAFE_READ_ERROR
)
584 error (0, errno
, _("error reading %s"), quoteaf (filename
));
589 /* If we read any bytes at all, count the incomplete line
590 on files that don't end with a newline. */
591 if (last
->nbytes
&& last
->buffer
[last
->nbytes
- 1] != line_end
)
597 for (tmp
= first
; n_elide
< total_lines
- tmp
->nlines
; tmp
= tmp
->next
)
599 desired_pos
+= tmp
->nbytes
;
600 xwrite_stdout (tmp
->buffer
, tmp
->nbytes
);
601 total_lines
-= tmp
->nlines
;
604 /* Print the first 'total_lines - n_elide' lines of tmp->buffer. */
605 if (n_elide
< total_lines
)
607 size_t n
= total_lines
- n_elide
;
608 char const *buffer_end
= tmp
->buffer
+ tmp
->nbytes
;
609 char const *p
= tmp
->buffer
;
610 while (n
&& (p
= memchr (p
, line_end
, buffer_end
- p
)))
616 desired_pos
+= p
- tmp
->buffer
;
617 xwrite_stdout (tmp
->buffer
, p
- tmp
->buffer
);
628 if (0 <= current_pos
&& elseek (fd
, desired_pos
, SEEK_SET
, filename
) < 0)
633 /* Output all but the last N_LINES lines of the input stream defined by
634 FD, START_POS, and SIZE.
635 START_POS is the starting position of the read pointer for the file
636 associated with FD (may be nonzero).
637 SIZE is the file size in bytes.
638 Return true upon success.
639 Give a diagnostic and return false upon error.
641 NOTE: this code is very similar to that of tail.c's file_lines function.
642 Unfortunately, factoring out some common core looks like it'd result
643 in a less efficient implementation or a messy interface. */
645 elide_tail_lines_seekable (const char *pretty_filename
, int fd
,
647 off_t start_pos
, off_t size
)
653 /* Set 'bytes_read' to the size of the last, probably partial, buffer;
654 0 < 'bytes_read' <= 'BUFSIZ'. */
655 bytes_read
= (pos
- start_pos
) % BUFSIZ
;
658 /* Make 'pos' a multiple of 'BUFSIZ' (0 if the file is short), so that all
659 reads will be on block boundaries, which might increase efficiency. */
661 if (elseek (fd
, pos
, SEEK_SET
, pretty_filename
) < 0)
663 bytes_read
= safe_read (fd
, buffer
, bytes_read
);
664 if (bytes_read
== SAFE_READ_ERROR
)
666 error (0, errno
, _("error reading %s"), quoteaf (pretty_filename
));
670 /* n_lines == 0 case needs special treatment. */
671 const bool all_lines
= !n_lines
;
673 /* Count the incomplete line on files that don't end with a newline. */
674 if (n_lines
&& bytes_read
&& buffer
[bytes_read
- 1] != line_end
)
679 /* Scan backward, counting the newlines in this bufferfull. */
681 size_t n
= bytes_read
;
689 nl
= memrchr (buffer
, line_end
, n
);
697 /* If necessary, restore the file pointer and copy
698 input to output up to position, POS. */
701 enum Copy_fd_status err
;
702 if (elseek (fd
, start_pos
, SEEK_SET
, pretty_filename
) < 0)
705 err
= copy_fd (fd
, pos
- start_pos
);
706 if (err
!= COPY_FD_OK
)
708 diagnose_copy_fd_failure (err
, pretty_filename
);
713 /* Output the initial portion of the buffer
714 in which we found the desired newline byte. */
715 xwrite_stdout (buffer
, n
+ 1);
717 /* Set file pointer to the byte after what we've output. */
718 return 0 <= elseek (fd
, pos
+ n
+ 1, SEEK_SET
, pretty_filename
);
722 /* Not enough newlines in that bufferfull. */
723 if (pos
== start_pos
)
725 /* Not enough lines in the file. */
729 if (elseek (fd
, pos
, SEEK_SET
, pretty_filename
) < 0)
732 bytes_read
= safe_read (fd
, buffer
, BUFSIZ
);
733 if (bytes_read
== SAFE_READ_ERROR
)
735 error (0, errno
, _("error reading %s"), quoteaf (pretty_filename
));
739 /* FIXME: is this dead code?
740 Consider the test, pos == start_pos, above. */
746 /* For the file FILENAME with descriptor FD, output all but the last N_ELIDE
747 lines. If SIZE is nonnegative, this is a regular file positioned
748 at START_POS with SIZE bytes. Return true on success.
749 Give a diagnostic and return nonzero upon error. */
752 elide_tail_lines_file (const char *filename
, int fd
, uintmax_t n_elide
,
753 struct stat
const *st
, off_t current_pos
)
755 off_t size
= st
->st_size
;
756 if (presume_input_pipe
|| size
<= ST_BLKSIZE (*st
))
757 return elide_tail_lines_pipe (filename
, fd
, n_elide
, current_pos
);
760 /* Find the offset, OFF, of the Nth newline from the end,
761 but not counting the last byte of the file.
762 If found, write from current position to OFF, inclusive.
763 Otherwise, just return true. */
765 return (size
<= current_pos
766 || elide_tail_lines_seekable (filename
, fd
, n_elide
,
772 head_bytes (const char *filename
, int fd
, uintmax_t bytes_to_write
)
775 size_t bytes_to_read
= BUFSIZ
;
777 while (bytes_to_write
)
780 if (bytes_to_write
< bytes_to_read
)
781 bytes_to_read
= bytes_to_write
;
782 bytes_read
= safe_read (fd
, buffer
, bytes_to_read
);
783 if (bytes_read
== SAFE_READ_ERROR
)
785 error (0, errno
, _("error reading %s"), quoteaf (filename
));
790 xwrite_stdout (buffer
, bytes_read
);
791 bytes_to_write
-= bytes_read
;
797 head_lines (const char *filename
, int fd
, uintmax_t lines_to_write
)
801 while (lines_to_write
)
803 size_t bytes_read
= safe_read (fd
, buffer
, BUFSIZ
);
804 size_t bytes_to_write
= 0;
806 if (bytes_read
== SAFE_READ_ERROR
)
808 error (0, errno
, _("error reading %s"), quoteaf (filename
));
813 while (bytes_to_write
< bytes_read
)
814 if (buffer
[bytes_to_write
++] == line_end
&& --lines_to_write
== 0)
816 off_t n_bytes_past_EOL
= bytes_read
- bytes_to_write
;
817 /* If we have read more data than that on the specified number
818 of lines, try to seek back to the position we would have
819 gotten to had we been reading one byte at a time. */
820 if (lseek (fd
, -n_bytes_past_EOL
, SEEK_CUR
) < 0)
823 if (fstat (fd
, &st
) != 0 || S_ISREG (st
.st_mode
))
824 elseek (fd
, -n_bytes_past_EOL
, SEEK_CUR
, filename
);
828 xwrite_stdout (buffer
, bytes_to_write
);
834 head (const char *filename
, int fd
, uintmax_t n_units
, bool count_lines
,
838 write_header (filename
);
842 off_t current_pos
= -1;
844 if (fstat (fd
, &st
) != 0)
846 error (0, errno
, _("cannot fstat %s"),
850 if (! presume_input_pipe
&& usable_st_size (&st
))
852 current_pos
= elseek (fd
, 0, SEEK_CUR
, filename
);
857 return elide_tail_lines_file (filename
, fd
, n_units
, &st
, current_pos
);
859 return elide_tail_bytes_file (filename
, fd
, n_units
, &st
, current_pos
);
862 return head_lines (filename
, fd
, n_units
);
864 return head_bytes (filename
, fd
, n_units
);
868 head_file (const char *filename
, uintmax_t n_units
, bool count_lines
,
873 bool is_stdin
= STREQ (filename
, "-");
877 have_read_stdin
= true;
879 filename
= _("standard input");
880 if (O_BINARY
&& ! isatty (STDIN_FILENO
))
881 xfreopen (NULL
, "rb", stdin
);
885 fd
= open (filename
, O_RDONLY
| O_BINARY
);
888 error (0, errno
, _("cannot open %s for reading"), quoteaf (filename
));
893 ok
= head (filename
, fd
, n_units
, count_lines
, elide_from_end
);
894 if (!is_stdin
&& close (fd
) != 0)
896 error (0, errno
, _("failed to close %s"), quoteaf (filename
));
902 /* Convert a string of decimal digits, N_STRING, with an optional suffix
903 to an integral value. Upon successful conversion,
904 return that value. If it cannot be converted, give a diagnostic and exit.
905 COUNT_LINES indicates whether N_STRING is a number of bytes or a number
906 of lines. It is used solely to give a more specific diagnostic. */
909 string_to_integer (bool count_lines
, const char *n_string
)
911 return xdectoumax (n_string
, 0, UINTMAX_MAX
, "bkKmMGTPEZY0",
912 count_lines
? _("invalid number of lines")
913 : _("invalid number of bytes"), 0);
917 main (int argc
, char **argv
)
919 enum header_mode header_mode
= multiple_files
;
924 /* Number of items to print. */
925 uintmax_t n_units
= DEFAULT_NUMBER
;
927 /* If true, interpret the numeric argument as the number of lines.
928 Otherwise, interpret it as the number of bytes. */
929 bool count_lines
= true;
931 /* Elide the specified number of lines or bytes, counting from
932 the end of the file. */
933 bool elide_from_end
= false;
935 /* Initializer for file_list if no file-arguments
936 were specified on the command line. */
937 static char const *const default_file_list
[] = {"-", NULL
};
938 char const *const *file_list
;
940 initialize_main (&argc
, &argv
);
941 set_program_name (argv
[0]);
942 setlocale (LC_ALL
, "");
943 bindtextdomain (PACKAGE
, LOCALEDIR
);
944 textdomain (PACKAGE
);
946 atexit (close_stdout
);
948 have_read_stdin
= false;
950 print_headers
= false;
954 if (1 < argc
&& argv
[1][0] == '-' && ISDIGIT (argv
[1][1]))
957 char *n_string
= ++a
;
959 char multiplier_char
= 0;
961 /* Old option syntax; a dash, one or more digits, and one or
962 more option letters. Move past the number. */
964 while (ISDIGIT (*a
));
966 /* Pointer to the byte after the last digit. */
969 /* Parse any appended option letters. */
983 multiplier_char
= *a
;
995 header_mode
= always
;
1003 error (0, 0, _("invalid trailing option -- %c"), *a
);
1004 usage (EXIT_FAILURE
);
1008 /* Append the multiplier character (if any) onto the end of
1009 the digit string. Then add NUL byte if necessary. */
1010 *end_n_string
= multiplier_char
;
1011 if (multiplier_char
)
1012 *(++end_n_string
) = 0;
1014 n_units
= string_to_integer (count_lines
, n_string
);
1016 /* Make the options we just parsed invisible to getopt. */
1022 while ((c
= getopt_long (argc
, argv
, "c:n:qvz0123456789", long_options
, NULL
))
1027 case PRESUME_INPUT_PIPE_OPTION
:
1028 presume_input_pipe
= true;
1032 count_lines
= false;
1033 elide_from_end
= (*optarg
== '-');
1036 n_units
= string_to_integer (count_lines
, optarg
);
1041 elide_from_end
= (*optarg
== '-');
1044 n_units
= string_to_integer (count_lines
, optarg
);
1048 header_mode
= never
;
1052 header_mode
= always
;
1059 case_GETOPT_HELP_CHAR
;
1061 case_GETOPT_VERSION_CHAR (PROGRAM_NAME
, AUTHORS
);
1065 error (0, 0, _("invalid trailing option -- %c"), c
);
1066 usage (EXIT_FAILURE
);
1070 if (header_mode
== always
1071 || (header_mode
== multiple_files
&& optind
< argc
- 1))
1072 print_headers
= true;
1074 if ( ! count_lines
&& elide_from_end
&& OFF_T_MAX
< n_units
)
1076 char umax_buf
[INT_BUFSIZE_BOUND (n_units
)];
1077 error (EXIT_FAILURE
, EOVERFLOW
, "%s: %s", _("invalid number of bytes"),
1078 quote (umaxtostr (n_units
, umax_buf
)));
1081 file_list
= (optind
< argc
1082 ? (char const *const *) &argv
[optind
]
1083 : default_file_list
);
1085 if (O_BINARY
&& ! isatty (STDOUT_FILENO
))
1086 xfreopen (NULL
, "wb", stdout
);
1088 for (i
= 0; file_list
[i
]; ++i
)
1089 ok
&= head_file (file_list
[i
], n_units
, count_lines
, elide_from_end
);
1091 if (have_read_stdin
&& close (STDIN_FILENO
) < 0)
1092 error (EXIT_FAILURE
, errno
, "-");
1094 return ok
? EXIT_SUCCESS
: EXIT_FAILURE
;