1 /* head -- output first part of file(s)
2 Copyright (C) 89, 90, 91, 1995-2003 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 2, or (at your option)
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, write to the Free Software Foundation,
16 Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
18 /* Options: (see usage)
19 Reads from standard input if no files are given or when a filename of
21 By default, filename headers are printed only if more than one file
23 By default, prints the first 10 lines (head -n 10).
25 David MacKenzie <djm@gnu.ai.mit.edu> */
31 #include <sys/types.h>
36 #include "full-write.h"
37 #include "full-read.h"
41 #include "safe-read.h"
44 /* The official name of this program (e.g., no `g' prefix). */
45 #define PROGRAM_NAME "head"
47 #define AUTHORS "David MacKenzie", "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 nonzero, 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 int presume_input_pipe
;
58 /* If nonzero, print filename headers. */
59 static int print_headers
;
61 /* When to print the filename banners. */
64 multiple_files
, always
, never
67 /* Options corresponding to header_mode values. */
68 static char const header_mode_option
[][4] = { "", " -v", " -q" };
70 /* The name this program was run with. */
73 /* Have we ever read standard input? */
74 static int have_read_stdin
;
81 COPY_FD_UNEXPECTED_EOF
84 /* For long options that have no equivalent short option, use a
85 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
88 PRESUME_INPUT_PIPE_OPTION
= CHAR_MAX
+ 1
91 static struct option
const long_options
[] =
93 {"bytes", required_argument
, NULL
, 'c'},
94 {"lines", required_argument
, NULL
, 'n'},
95 {"presume-input-pipe", no_argument
, NULL
,
96 PRESUME_INPUT_PIPE_OPTION
}, /* do not document */
97 {"quiet", no_argument
, NULL
, 'q'},
98 {"silent", no_argument
, NULL
, 'q'},
99 {"verbose", no_argument
, NULL
, 'v'},
100 {GETOPT_HELP_OPTION_DECL
},
101 {GETOPT_VERSION_OPTION_DECL
},
109 fprintf (stderr
, _("Try `%s --help' for more information.\n"),
114 Usage: %s [OPTION]... [FILE]...\n\
118 Print the first 10 lines of each FILE to standard output.\n\
119 With more than one FILE, precede each with a header giving the file name.\n\
120 With no FILE, or when FILE is -, read standard input.\n\
124 Mandatory arguments to long options are mandatory for short options too.\n\
127 -c, --bytes=[-]N print the first N bytes of each file;\n\
128 with the leading `-', print all but the last\n\
129 N bytes of each file\n\
130 -n, --lines=[-]N print the first N lines instead of the first 10;\n\
131 with the leading `-', print all but the last\n\
132 N lines of each file\n\
135 -q, --quiet, --silent never print headers giving file names\n\
136 -v, --verbose always print headers giving file names\n\
138 fputs (HELP_OPTION_DESCRIPTION
, stdout
);
139 fputs (VERSION_OPTION_DESCRIPTION
, stdout
);
142 N may have a multiplier suffix: b 512, k 1024, m 1024*1024.\n\
144 printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT
);
146 exit (status
== 0 ? EXIT_SUCCESS
: EXIT_FAILURE
);
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"), quote (filename
));
157 case COPY_FD_WRITE_ERROR
:
158 error (0, errno
, _("error writing %s"), quote (filename
));
160 case COPY_FD_UNEXPECTED_EOF
:
161 error (0, errno
, _("%s: file has shrunk too much"), quote (filename
));
169 write_header (const char *filename
)
171 static int first_file
= 1;
173 printf ("%s==> %s <==\n", (first_file
? "" : "\n"), filename
);
177 /* Copy no more than N_BYTES from file descriptor SRC_FD to O_STREAM.
178 Return an appropriate indication of success or failure. */
180 static enum Copy_fd_status
181 copy_fd (int src_fd
, FILE *o_stream
, uintmax_t n_bytes
)
184 const size_t buf_size
= sizeof (buf
);
186 /* Copy the file contents. */
189 size_t n_to_read
= MIN (buf_size
, n_bytes
);
190 size_t n_read
= safe_read (src_fd
, buf
, n_to_read
);
191 if (n_read
== SAFE_READ_ERROR
)
192 return COPY_FD_READ_ERROR
;
196 if (n_read
== 0 && n_bytes
!= 0)
197 return COPY_FD_UNEXPECTED_EOF
;
199 if (fwrite (buf
, 1, n_read
, o_stream
) < n_read
)
200 return COPY_FD_WRITE_ERROR
;
206 /* Print all but the last N_ELIDE lines from the input available via
207 the non-seekable file descriptor FD. Return zero upon success.
208 Give a diagnostic and return nonzero upon error. */
210 elide_tail_bytes_pipe (const char *filename
, int fd
, uintmax_t n_elide_0
)
212 size_t n_elide
= n_elide_0
;
214 #ifndef HEAD_TAIL_PIPE_READ_BUFSIZE
215 # define HEAD_TAIL_PIPE_READ_BUFSIZE BUFSIZ
217 #define READ_BUFSIZE HEAD_TAIL_PIPE_READ_BUFSIZE
219 /* If we're eliding no more than this many bytes, then it's ok to allocate
220 more memory in order to use a more time-efficient algorithm.
221 FIXME: use a fraction of available memory instead, as in sort.
222 FIXME: is this even worthwhile? */
223 #ifndef HEAD_TAIL_PIPE_BYTECOUNT_THRESHOLD
224 # define HEAD_TAIL_PIPE_BYTECOUNT_THRESHOLD 1024 * 1024
227 #if HEAD_TAIL_PIPE_BYTECOUNT_THRESHOLD < 2 * READ_BUFSIZE
228 "HEAD_TAIL_PIPE_BYTECOUNT_THRESHOLD must be at least 2 * READ_BUFSIZE"
231 if (SIZE_MAX
< n_elide_0
+ READ_BUFSIZE
)
233 char umax_buf
[INT_BUFSIZE_BOUND (uintmax_t)];
234 error (EXIT_FAILURE
, 0, _("%s: number of bytes is large"),
235 umaxtostr (n_elide_0
, umax_buf
));
238 /* Two cases to consider...
239 1) n_elide is small enough that we can afford to double-buffer:
240 allocate 2 * (READ_BUFSIZE + n_elide) bytes
241 2) n_elide is too big for that, so we allocate only
242 (READ_BUFSIZE + n_elide) bytes
244 FIXME: profile, to see if double-buffering is worthwhile
246 CAUTION: do not fail (out of memory) when asked to elide
247 a ridiculous amount, but when given only a small input. */
249 if (n_elide
<= HEAD_TAIL_PIPE_BYTECOUNT_THRESHOLD
)
254 size_t n_to_read
= READ_BUFSIZE
+ n_elide
;
257 b
[0] = xmalloc (2 * n_to_read
);
258 b
[1] = b
[0] + n_to_read
;
260 for (i
= 0; ! eof
; i
= !i
)
262 size_t n_read
= full_read (fd
, b
[i
], n_to_read
);
264 if (n_read
< n_to_read
)
268 error (0, errno
, _("error reading %s"), quote (filename
));
274 if (n_read
<= n_elide
)
278 /* The input is no larger than the number of bytes
279 to elide. So there's nothing to output, and
284 delta
= n_elide
- n_read
;
290 /* Output any (but maybe just part of the) elided data from
291 the previous round. */
294 /* Don't bother checking for errors here.
295 If there's a failure, the test of the following
296 fwrite or in close_stdout will catch it. */
297 fwrite (b
[!i
] + READ_BUFSIZE
, 1, n_elide
- delta
, stdout
);
302 && fwrite (b
[i
], 1, n_read
- n_elide
, stdout
) < n_read
- n_elide
)
304 error (0, errno
, _("write error"));
315 /* Read blocks of size READ_BUFSIZE, until we've read at least n_elide
316 bytes. Then, for each new buffer we read, also write an old one. */
321 bool buffered_enough
;
324 /* Round n_elide up to a multiple of READ_BUFSIZE. */
325 size_t rem
= READ_BUFSIZE
- (n_elide
% READ_BUFSIZE
);
326 size_t n_elide_round
= n_elide
+ rem
;
327 size_t n_bufs
= n_elide_round
/ READ_BUFSIZE
+ 1;
328 b
= xcalloc (n_bufs
, sizeof *b
);
330 buffered_enough
= false;
331 for (i
= 0, i_next
= 1; !eof
; i
= i_next
, i_next
= (i_next
+ 1) % n_bufs
)
334 b
[i
] = xmalloc (READ_BUFSIZE
);
335 n_read
= full_read (fd
, b
[i
], READ_BUFSIZE
);
336 if (n_read
< READ_BUFSIZE
)
340 error (0, errno
, _("error reading %s"), quote (filename
));
348 buffered_enough
= true;
352 if (fwrite (b
[i_next
], 1, n_read
, stdout
) < n_read
)
354 error (0, errno
, _("write error"));
361 /* Output any remainder: rem bytes from b[i] + n_read. */
366 size_t n_bytes_left_in_b_i
= READ_BUFSIZE
- n_read
;
367 if (rem
< n_bytes_left_in_b_i
)
369 fwrite (b
[i
] + n_read
, 1, rem
, stdout
);
373 fwrite (b
[i
] + n_read
, 1, n_bytes_left_in_b_i
, stdout
);
374 fwrite (b
[i_next
], 1, rem
- n_bytes_left_in_b_i
, stdout
);
377 else if (i
+ 1 == n_bufs
)
379 /* This happens when n_elide < file_size < n_elide_round.
383 |---------!---------!---------!---------|
384 |---- n_elide ---------|
387 |---- file size -----------|
389 |---- n_elide_round ----------|
391 size_t y
= READ_BUFSIZE
- rem
;
392 size_t x
= n_read
- y
;
393 fwrite (b
[i_next
], 1, x
, stdout
);
398 for (i
= 0; i
< n_bufs
; i
++)
407 /* Print all but the last N_ELIDE lines from the input available
408 via file descriptor FD. Return zero upon success.
409 Give a diagnostic and return nonzero upon error. */
411 /* NOTE: if the input file shrinks by more than N_ELIDE bytes between
412 the length determination and the actual reading, then head fails. */
415 elide_tail_bytes_file (const char *filename
, int fd
, uintmax_t n_elide
)
419 /* We need binary input, since `head' relies on `lseek' and byte counts,
420 while binary output will preserve the style (Unix/DOS) of text file. */
421 SET_BINARY2 (fd
, STDOUT_FILENO
);
423 if (presume_input_pipe
|| fstat (fd
, &stats
) || ! S_ISREG (stats
.st_mode
))
425 return elide_tail_bytes_pipe (filename
, fd
, n_elide
);
429 off_t current_pos
, end_pos
;
430 uintmax_t bytes_remaining
;
432 enum Copy_fd_status err
;
434 if ((current_pos
= lseek (fd
, (off_t
) 0, SEEK_CUR
)) == -1
435 || (end_pos
= lseek (fd
, (off_t
) 0, SEEK_END
)) == -1)
437 error (0, errno
, _("cannot lseek %s"), quote (filename
));
441 /* Be careful here. The current position may actually be
442 beyond the end of the file. */
443 bytes_remaining
= (diff
= end_pos
- current_pos
) < 0 ? 0 : diff
;
445 if (bytes_remaining
<= n_elide
)
448 /* Seek back to `current' position, then copy the required
449 number of bytes from fd. */
450 if (lseek (fd
, (off_t
) 0, current_pos
) == -1)
452 error (0, errno
, _("%s: cannot lseek back to original position"),
457 err
= copy_fd (fd
, stdout
, bytes_remaining
- n_elide
);
458 if (err
== COPY_FD_OK
)
461 diagnose_copy_fd_failure (err
, filename
);
466 /* Print all but the last N_ELIDE lines from the input stream
467 open for reading via file descriptor FD.
468 Buffer the specified number of lines as a linked list of LBUFFERs,
469 adding them as needed. Return 0 if successful, 1 upon error. */
472 elide_tail_lines_pipe (const char *filename
, int fd
, uintmax_t n_elide
)
479 struct linebuffer
*next
;
481 typedef struct linebuffer LBUFFER
;
482 LBUFFER
*first
, *last
, *tmp
;
483 size_t total_lines
= 0; /* Total number of newlines in all buffers. */
485 size_t n_read
; /* Size in bytes of most recent read */
487 first
= last
= xmalloc (sizeof (LBUFFER
));
488 first
->nbytes
= first
->nlines
= 0;
490 tmp
= xmalloc (sizeof (LBUFFER
));
492 /* Always read into a fresh buffer.
493 Read, (producing no output) until we've accumulated at least
494 n_elide newlines, or until EOF, whichever comes first. */
497 n_read
= safe_read (fd
, tmp
->buffer
, BUFSIZ
);
498 if (n_read
== 0 || n_read
== SAFE_READ_ERROR
)
500 tmp
->nbytes
= n_read
;
504 /* Count the number of newlines just read. */
506 char const *buffer_end
= tmp
->buffer
+ n_read
;
507 char const *p
= tmp
->buffer
;
508 while ((p
= memchr (p
, '\n', buffer_end
- p
)))
514 total_lines
+= tmp
->nlines
;
516 /* If there is enough room in the last buffer read, just append the new
517 one to it. This is because when reading from a pipe, `n_read' can
518 often be very small. */
519 if (tmp
->nbytes
+ last
->nbytes
< BUFSIZ
)
521 memcpy (&last
->buffer
[last
->nbytes
], tmp
->buffer
, tmp
->nbytes
);
522 last
->nbytes
+= tmp
->nbytes
;
523 last
->nlines
+= tmp
->nlines
;
527 /* If there's not enough room, link the new buffer onto the end of
528 the list, then either free up the oldest buffer for the next
529 read if that would leave enough lines, or else malloc a new one.
530 Some compaction mechanism is possible but probably not
532 last
= last
->next
= tmp
;
533 if (n_elide
< total_lines
- first
->nlines
)
535 fwrite (first
->buffer
, 1, first
->nbytes
, stdout
);
537 total_lines
-= first
->nlines
;
541 tmp
= xmalloc (sizeof (LBUFFER
));
547 if (n_read
== SAFE_READ_ERROR
)
549 error (0, errno
, _("error reading %s"), quote (filename
));
554 /* If we read any bytes at all, count the incomplete line
555 on files that don't end with a newline. */
556 if (last
->nbytes
&& last
->buffer
[last
->nbytes
- 1] != '\n')
562 for (tmp
= first
; n_elide
< total_lines
- tmp
->nlines
; tmp
= tmp
->next
)
564 fwrite (tmp
->buffer
, 1, tmp
->nbytes
, stdout
);
565 total_lines
-= tmp
->nlines
;
568 /* Print the first `total_lines - n_elide' lines of tmp->buffer. */
569 if (n_elide
< total_lines
)
571 size_t n
= total_lines
- n_elide
;
572 char const *buffer_end
= tmp
->buffer
+ tmp
->nbytes
;
573 char const *p
= tmp
->buffer
;
574 while (n
&& (p
= memchr (p
, '\n', buffer_end
- p
)))
580 fwrite (tmp
->buffer
, 1, p
- tmp
->buffer
, stdout
);
593 /* Output all but the last N_LINES lines of the input stream defined by
594 FD, START_POS, and END_POS.
595 START_POS is the starting position of the read pointer for the file
596 associated with FD (may be nonzero).
597 END_POS is the file offset of EOF (one larger than offset of last byte).
598 Return zero upon success.
599 Give a diagnostic and return nonzero upon error.
601 NOTE: this code is very similar to that of tail.c's file_lines function.
602 Unfortunately, factoring out some common core looks like it'd result
603 in a less efficient implementation or a messy interface. */
605 elide_tail_lines_seekable (const char *pretty_filename
, int fd
,
607 off_t start_pos
, off_t end_pos
)
613 /* Set `bytes_read' to the size of the last, probably partial, buffer;
614 0 < `bytes_read' <= `BUFSIZ'. */
615 bytes_read
= (pos
- start_pos
) % BUFSIZ
;
618 /* Make `pos' a multiple of `BUFSIZ' (0 if the file is short), so that all
619 reads will be on block boundaries, which might increase efficiency. */
621 if (lseek (fd
, pos
, SEEK_SET
) < 0)
623 char offset_buf
[INT_BUFSIZE_BOUND (off_t
)];
624 error (0, errno
, _("%s: cannot seek to offset %s"),
625 pretty_filename
, offtostr (pos
, offset_buf
));
628 bytes_read
= safe_read (fd
, buffer
, bytes_read
);
629 if (bytes_read
== SAFE_READ_ERROR
)
631 error (0, errno
, _("error reading %s"), quote (pretty_filename
));
635 /* Count the incomplete line on files that don't end with a newline. */
636 if (bytes_read
&& buffer
[bytes_read
- 1] != '\n')
641 /* Scan backward, counting the newlines in this bufferfull. */
643 size_t n
= bytes_read
;
647 nl
= memrchr (buffer
, '\n', n
);
654 /* If necessary, restore the file pointer and copy
655 input to output up to position, POS. */
658 enum Copy_fd_status err
;
659 if (lseek (fd
, start_pos
, SEEK_SET
) < 0)
661 /* Failed to reposition file pointer. */
663 "%s: unable to restore file pointer to initial offset",
664 quote (pretty_filename
));
668 err
= copy_fd (fd
, stdout
, pos
- start_pos
);
669 if (err
!= COPY_FD_OK
)
671 diagnose_copy_fd_failure (err
, pretty_filename
);
676 /* Output the initial portion of the buffer
677 in which we found the desired newline byte.
678 Don't bother testing for failure for such a small amount.
679 Any failure will be detected upon close. */
680 fwrite (buffer
, 1, n
+ 1, stdout
);
685 /* Not enough newlines in that bufferfull. */
686 if (pos
== start_pos
)
688 /* Not enough lines in the file. */
692 if (lseek (fd
, pos
, SEEK_SET
) < 0)
694 char offset_buf
[INT_BUFSIZE_BOUND (off_t
)];
695 error (0, errno
, _("%s: cannot seek to offset %s"),
696 pretty_filename
, offtostr (pos
, offset_buf
));
700 bytes_read
= safe_read (fd
, buffer
, BUFSIZ
);
701 if (bytes_read
== SAFE_READ_ERROR
)
703 error (0, errno
, _("error reading %s"), quote (pretty_filename
));
707 /* FIXME: is this dead code?
708 Consider the test, pos == start_pos, above. */
714 /* Print all but the last N_ELIDE lines from the input available
715 via file descriptor FD. Return zero upon success.
716 Give a diagnostic and return nonzero upon error. */
719 elide_tail_lines_file (const char *filename
, int fd
, uintmax_t n_elide
)
721 /* We need binary input, since `head' relies on `lseek' and byte counts,
722 while binary output will preserve the style (Unix/DOS) of text file. */
723 SET_BINARY2 (fd
, STDOUT_FILENO
);
725 if (!presume_input_pipe
)
727 /* Find the offset, OFF, of the Nth newline from the end,
728 but not counting the last byte of the file.
729 If found, write from current position to OFF, inclusive.
730 Otherwise, just return 0. */
732 off_t start_pos
= lseek (fd
, (off_t
) 0, SEEK_CUR
);
733 off_t end_pos
= lseek (fd
, (off_t
) 0, SEEK_END
);
734 if (0 <= start_pos
&& start_pos
< end_pos
)
736 /* If the file is empty, we're done. */
740 return elide_tail_lines_seekable (filename
, fd
, n_elide
,
744 /* lseek failed or the end offset precedes start.
748 return elide_tail_lines_pipe (filename
, fd
, n_elide
);
752 head_bytes (const char *filename
, int fd
, uintmax_t bytes_to_write
)
755 size_t bytes_to_read
= BUFSIZ
;
757 /* Need BINARY I/O for the byte counts to be accurate. */
758 SET_BINARY2 (fd
, fileno (stdout
));
760 while (bytes_to_write
)
763 if (bytes_to_write
< bytes_to_read
)
764 bytes_to_read
= bytes_to_write
;
765 bytes_read
= safe_read (fd
, buffer
, bytes_to_read
);
766 if (bytes_read
== SAFE_READ_ERROR
)
768 error (0, errno
, _("error reading %s"), quote (filename
));
773 if (fwrite (buffer
, 1, bytes_read
, stdout
) < bytes_read
)
774 error (EXIT_FAILURE
, errno
, _("write error"));
775 bytes_to_write
-= bytes_read
;
781 head_lines (const char *filename
, int fd
, uintmax_t lines_to_write
)
785 /* Need BINARY I/O for the byte counts to be accurate. */
786 /* FIXME: do we really need this when counting *lines*? */
787 SET_BINARY2 (fd
, fileno (stdout
));
789 while (lines_to_write
)
791 size_t bytes_read
= safe_read (fd
, buffer
, BUFSIZ
);
792 size_t bytes_to_write
= 0;
794 if (bytes_read
== SAFE_READ_ERROR
)
796 error (0, errno
, _("error reading %s"), quote (filename
));
801 while (bytes_to_write
< bytes_read
)
802 if (buffer
[bytes_to_write
++] == '\n' && --lines_to_write
== 0)
804 off_t n_bytes_past_EOL
= bytes_read
- bytes_to_write
;
805 /* If we have read more data than that on the specified number
806 of lines, try to seek back to the position we would have
807 gotten to had we been reading one byte at a time. */
808 if (lseek (fd
, -n_bytes_past_EOL
, SEEK_CUR
) < 0)
812 if (fstat (fd
, &st
) != 0 || S_ISREG (st
.st_mode
))
813 error (0, e
, _("cannot reposition file pointer for %s"),
818 if (fwrite (buffer
, 1, bytes_to_write
, stdout
) < bytes_to_write
)
819 error (EXIT_FAILURE
, errno
, _("write error"));
825 head (const char *filename
, int fd
, uintmax_t n_units
, int count_lines
,
829 write_header (filename
);
835 return elide_tail_lines_file (filename
, fd
, n_units
);
839 return elide_tail_bytes_file (filename
, fd
, n_units
);
843 return head_lines (filename
, fd
, n_units
);
845 return head_bytes (filename
, fd
, n_units
);
849 head_file (const char *filename
, uintmax_t n_units
, int count_lines
,
855 if (STREQ (filename
, "-"))
859 filename
= _("standard input");
863 fd
= open (filename
, O_RDONLY
);
866 error (0, errno
, _("cannot open %s for reading"), quote (filename
));
871 fail
= head (filename
, fd
, n_units
, count_lines
, elide_from_end
);
872 if (fd
!= STDIN_FILENO
&& close (fd
) == -1)
874 error (0, errno
, _("closing %s"), quote (filename
));
880 /* Convert a string of decimal digits, N_STRING, with a single, optional suffix
881 character (b, k, or m) to an integral value. Upon successful conversion,
882 return that value. If it cannot be converted, give a diagnostic and exit.
883 COUNT_LINES indicates whether N_STRING is a number of bytes or a number
884 of lines. It is used solely to give a more specific diagnostic. */
887 string_to_integer (int count_lines
, const char *n_string
)
892 s_err
= xstrtoumax (n_string
, NULL
, 10, &n
, "bkm");
894 if (s_err
== LONGINT_OVERFLOW
)
896 error (EXIT_FAILURE
, 0,
897 _("%s: %s is so large that it is not representable"), n_string
,
898 count_lines
? _("number of lines") : _("number of bytes"));
901 if (s_err
!= LONGINT_OK
)
903 error (EXIT_FAILURE
, 0, "%s: %s", n_string
,
905 ? _("invalid number of lines")
906 : _("invalid number of bytes")));
913 main (int argc
, char **argv
)
915 enum header_mode header_mode
= multiple_files
;
920 /* Number of items to print. */
921 uintmax_t n_units
= DEFAULT_NUMBER
;
923 /* If nonzero, interpret the numeric argument as the number of lines.
924 Otherwise, interpret it as the number of bytes. */
927 /* Elide the specified number of lines or bytes, counting from
928 the end of the file. */
929 int elide_from_end
= 0;
931 /* Initializer for file_list if no file-arguments
932 were specified on the command line. */
933 static char const *const default_file_list
[] = {"-", NULL
};
934 char const *const *file_list
;
936 initialize_main (&argc
, &argv
);
937 program_name
= argv
[0];
938 setlocale (LC_ALL
, "");
939 bindtextdomain (PACKAGE
, LOCALEDIR
);
940 textdomain (PACKAGE
);
942 atexit (close_stdout
);
948 if (1 < argc
&& argv
[1][0] == '-' && ISDIGIT (argv
[1][1]))
951 char *n_string
= ++a
;
953 char multiplier_char
= 0;
955 /* Old option syntax; a dash, one or more digits, and one or
956 more option letters. Move past the number. */
958 while (ISDIGIT (*a
));
960 /* Pointer to the byte after the last digit. */
963 /* Parse any appended option letters. */
977 multiplier_char
= *a
;
989 header_mode
= always
;
993 error (0, 0, _("unrecognized option `-%c'"), *a
);
994 usage (EXIT_FAILURE
);
998 if (200112 <= posix2_version ())
1000 error (0, 0, _("`-%s' option is obsolete; use `-%c %.*s%.*s%s'"),
1001 n_string
, count_lines
? 'n' : 'c',
1002 (int) (end_n_string
- n_string
), n_string
,
1003 multiplier_char
!= 0, &multiplier_char
,
1004 header_mode_option
[header_mode
]);
1005 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. */
1021 /* FIXME: allow POSIX options if there were obsolescent ones? */
1025 while ((c
= getopt_long (argc
, argv
, "c:n:qv", long_options
, NULL
)) != -1)
1032 case PRESUME_INPUT_PIPE_OPTION
:
1033 presume_input_pipe
= 1;
1038 elide_from_end
= (*optarg
== '-');
1041 n_units
= string_to_integer (count_lines
, optarg
);
1046 elide_from_end
= (*optarg
== '-');
1049 n_units
= string_to_integer (count_lines
, optarg
);
1053 header_mode
= never
;
1057 header_mode
= always
;
1060 case_GETOPT_HELP_CHAR
;
1062 case_GETOPT_VERSION_CHAR (PROGRAM_NAME
, AUTHORS
);
1065 usage (EXIT_FAILURE
);
1069 if (header_mode
== always
1070 || (header_mode
== multiple_files
&& optind
< argc
- 1))
1073 if ( ! count_lines
&& elide_from_end
&& OFF_T_MAX
< n_units
)
1075 char umax_buf
[INT_BUFSIZE_BOUND (uintmax_t)];
1076 error (EXIT_FAILURE
, 0, _("%s: number of bytes is too large"),
1077 umaxtostr (n_units
, umax_buf
));
1080 file_list
= (optind
< argc
1081 ? (char const *const *) &argv
[optind
]
1082 : default_file_list
);
1084 for (i
= 0; file_list
[i
]; ++i
)
1085 exit_status
|= head_file (file_list
[i
], n_units
, count_lines
,
1088 if (have_read_stdin
&& close (STDIN_FILENO
) < 0)
1089 error (EXIT_FAILURE
, errno
, "-");
1091 exit (exit_status
== 0 ? EXIT_SUCCESS
: EXIT_FAILURE
);