maint: improve error messages upon failed read, write, access, close
[platform/upstream/coreutils.git] / src / head.c
1 /* head -- output first part of file(s)
2    Copyright (C) 1989-2013 Free Software Foundation, Inc.
3
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.
8
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.
13
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/>.  */
16
17 /* Options: (see usage)
18    Reads from standard input if no files are given or when a filename of
19    ''-'' is encountered.
20    By default, filename headers are printed only if more than one file
21    is given.
22    By default, prints the first 10 lines (head -n 10).
23
24    David MacKenzie <djm@gnu.ai.mit.edu> */
25
26 #include <config.h>
27
28 #include <stdio.h>
29 #include <getopt.h>
30 #include <sys/types.h>
31
32 #include "system.h"
33
34 #include "error.h"
35 #include "full-read.h"
36 #include "quote.h"
37 #include "safe-read.h"
38 #include "xfreopen.h"
39 #include "xstrtol.h"
40
41 /* The official name of this program (e.g., no 'g' prefix).  */
42 #define PROGRAM_NAME "head"
43
44 #define AUTHORS \
45   proper_name ("David MacKenzie"), \
46   proper_name ("Jim Meyering")
47
48 /* Number of lines/chars/blocks to head. */
49 #define DEFAULT_NUMBER 10
50
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;
56
57 /* If true, print filename headers. */
58 static bool print_headers;
59
60 /* When to print the filename banners. */
61 enum header_mode
62 {
63   multiple_files, always, never
64 };
65
66 /* Have we ever read standard input?  */
67 static bool have_read_stdin;
68
69 enum Copy_fd_status
70   {
71     COPY_FD_OK = 0,
72     COPY_FD_READ_ERROR,
73     COPY_FD_WRITE_ERROR,
74     COPY_FD_UNEXPECTED_EOF
75   };
76
77 /* For long options that have no equivalent short option, use a
78    non-character as a pseudo short option, starting with CHAR_MAX + 1.  */
79 enum
80 {
81   PRESUME_INPUT_PIPE_OPTION = CHAR_MAX + 1
82 };
83
84 static struct option const long_options[] =
85 {
86   {"bytes", required_argument, NULL, 'c'},
87   {"lines", required_argument, NULL, 'n'},
88   {"-presume-input-pipe", no_argument, NULL,
89    PRESUME_INPUT_PIPE_OPTION}, /* do not document */
90   {"quiet", no_argument, NULL, 'q'},
91   {"silent", no_argument, NULL, 'q'},
92   {"verbose", no_argument, NULL, 'v'},
93   {GETOPT_HELP_OPTION_DECL},
94   {GETOPT_VERSION_OPTION_DECL},
95   {NULL, 0, NULL, 0}
96 };
97
98 void
99 usage (int status)
100 {
101   if (status != EXIT_SUCCESS)
102     emit_try_help ();
103   else
104     {
105       printf (_("\
106 Usage: %s [OPTION]... [FILE]...\n\
107 "),
108               program_name);
109       fputs (_("\
110 Print the first 10 lines of each FILE to standard output.\n\
111 With more than one FILE, precede each with a header giving the file name.\n\
112 With no FILE, or when FILE is -, read standard input.\n\
113 "), stdout);
114
115       emit_mandatory_arg_note ();
116
117       fputs (_("\
118   -c, --bytes=[-]K         print the first K bytes of each file;\n\
119                              with the leading '-', print all but the last\n\
120                              K bytes of each file\n\
121   -n, --lines=[-]K         print the first K lines instead of the first 10;\n\
122                              with the leading '-', print all but the last\n\
123                              K lines of each file\n\
124 "), stdout);
125       fputs (_("\
126   -q, --quiet, --silent    never print headers giving file names\n\
127   -v, --verbose            always print headers giving file names\n\
128 "), stdout);
129       fputs (HELP_OPTION_DESCRIPTION, stdout);
130       fputs (VERSION_OPTION_DESCRIPTION, stdout);
131       fputs (_("\
132 \n\
133 K may have a multiplier suffix:\n\
134 b 512, kB 1000, K 1024, MB 1000*1000, M 1024*1024,\n\
135 GB 1000*1000*1000, G 1024*1024*1024, and so on for T, P, E, Z, Y.\n\
136 "), stdout);
137       emit_ancillary_info ();
138     }
139   exit (status);
140 }
141
142 static void
143 diagnose_copy_fd_failure (enum Copy_fd_status err, char const *filename)
144 {
145   switch (err)
146     {
147     case COPY_FD_READ_ERROR:
148       error (0, errno, _("error reading %s"), quote (filename));
149       break;
150     case COPY_FD_WRITE_ERROR:
151       error (0, errno, _("error writing %s"), quote (filename));
152       break;
153     case COPY_FD_UNEXPECTED_EOF:
154       error (0, errno, _("%s: file has shrunk too much"), quote (filename));
155       break;
156     default:
157       abort ();
158     }
159 }
160
161 static void
162 write_header (const char *filename)
163 {
164   static bool first_file = true;
165
166   printf ("%s==> %s <==\n", (first_file ? "" : "\n"), filename);
167   first_file = false;
168 }
169
170 /* Copy no more than N_BYTES from file descriptor SRC_FD to O_STREAM.
171    Return an appropriate indication of success or failure. */
172
173 static enum Copy_fd_status
174 copy_fd (int src_fd, FILE *o_stream, uintmax_t n_bytes)
175 {
176   char buf[BUFSIZ];
177   const size_t buf_size = sizeof (buf);
178
179   /* Copy the file contents.  */
180   while (0 < n_bytes)
181     {
182       size_t n_to_read = MIN (buf_size, n_bytes);
183       size_t n_read = safe_read (src_fd, buf, n_to_read);
184       if (n_read == SAFE_READ_ERROR)
185         return COPY_FD_READ_ERROR;
186
187       n_bytes -= n_read;
188
189       if (n_read == 0 && n_bytes != 0)
190         return COPY_FD_UNEXPECTED_EOF;
191
192       if (fwrite (buf, 1, n_read, o_stream) < n_read)
193         return COPY_FD_WRITE_ERROR;
194     }
195
196   return COPY_FD_OK;
197 }
198
199 /* Print all but the last N_ELIDE lines from the input available via
200    the non-seekable file descriptor FD.  Return true upon success.
201    Give a diagnostic and return false upon error.  */
202 static bool
203 elide_tail_bytes_pipe (const char *filename, int fd, uintmax_t n_elide_0)
204 {
205   size_t n_elide = n_elide_0;
206
207 #ifndef HEAD_TAIL_PIPE_READ_BUFSIZE
208 # define HEAD_TAIL_PIPE_READ_BUFSIZE BUFSIZ
209 #endif
210 #define READ_BUFSIZE HEAD_TAIL_PIPE_READ_BUFSIZE
211
212   /* If we're eliding no more than this many bytes, then it's ok to allocate
213      more memory in order to use a more time-efficient algorithm.
214      FIXME: use a fraction of available memory instead, as in sort.
215      FIXME: is this even worthwhile?  */
216 #ifndef HEAD_TAIL_PIPE_BYTECOUNT_THRESHOLD
217 # define HEAD_TAIL_PIPE_BYTECOUNT_THRESHOLD 1024 * 1024
218 #endif
219
220 #if HEAD_TAIL_PIPE_BYTECOUNT_THRESHOLD < 2 * READ_BUFSIZE
221   "HEAD_TAIL_PIPE_BYTECOUNT_THRESHOLD must be at least 2 * READ_BUFSIZE"
222 #endif
223
224   if (SIZE_MAX < n_elide_0 + READ_BUFSIZE)
225     {
226       char umax_buf[INT_BUFSIZE_BOUND (n_elide_0)];
227       error (EXIT_FAILURE, 0, _("%s: number of bytes is too large"),
228              umaxtostr (n_elide_0, umax_buf));
229     }
230
231   /* Two cases to consider...
232      1) n_elide is small enough that we can afford to double-buffer:
233         allocate 2 * (READ_BUFSIZE + n_elide) bytes
234      2) n_elide is too big for that, so we allocate only
235         (READ_BUFSIZE + n_elide) bytes
236
237      FIXME: profile, to see if double-buffering is worthwhile
238
239      CAUTION: do not fail (out of memory) when asked to elide
240      a ridiculous amount, but when given only a small input.  */
241
242   if (n_elide <= HEAD_TAIL_PIPE_BYTECOUNT_THRESHOLD)
243     {
244       bool ok = true;
245       bool first = true;
246       bool eof = false;
247       size_t n_to_read = READ_BUFSIZE + n_elide;
248       bool i;
249       char *b[2];
250       b[0] = xnmalloc (2, n_to_read);
251       b[1] = b[0] + n_to_read;
252
253       for (i = false; ! eof ; i = !i)
254         {
255           size_t n_read = full_read (fd, b[i], n_to_read);
256           size_t delta = 0;
257           if (n_read < n_to_read)
258             {
259               if (errno != 0)
260                 {
261                   error (0, errno, _("error reading %s"), quote (filename));
262                   ok = false;
263                   break;
264                 }
265
266               /* reached EOF */
267               if (n_read <= n_elide)
268                 {
269                   if (first)
270                     {
271                       /* The input is no larger than the number of bytes
272                          to elide.  So there's nothing to output, and
273                          we're done.  */
274                     }
275                   else
276                     {
277                       delta = n_elide - n_read;
278                     }
279                 }
280               eof = true;
281             }
282
283           /* Output any (but maybe just part of the) elided data from
284              the previous round.  */
285           if ( ! first)
286             {
287               /* Don't bother checking for errors here.
288                  If there's a failure, the test of the following
289                  fwrite or in close_stdout will catch it.  */
290               fwrite (b[!i] + READ_BUFSIZE, 1, n_elide - delta, stdout);
291             }
292           first = false;
293
294           if (n_elide < n_read
295               && fwrite (b[i], 1, n_read - n_elide, stdout) < n_read - n_elide)
296             {
297               error (0, errno, _("write error"));
298               ok = false;
299               break;
300             }
301         }
302
303       free (b[0]);
304       return ok;
305     }
306   else
307     {
308       /* Read blocks of size READ_BUFSIZE, until we've read at least n_elide
309          bytes.  Then, for each new buffer we read, also write an old one.  */
310
311       bool ok = true;
312       bool eof = false;
313       size_t n_read;
314       bool buffered_enough;
315       size_t i, i_next;
316       char **b;
317       /* Round n_elide up to a multiple of READ_BUFSIZE.  */
318       size_t rem = READ_BUFSIZE - (n_elide % READ_BUFSIZE);
319       size_t n_elide_round = n_elide + rem;
320       size_t n_bufs = n_elide_round / READ_BUFSIZE + 1;
321       b = xcalloc (n_bufs, sizeof *b);
322
323       buffered_enough = false;
324       for (i = 0, i_next = 1; !eof; i = i_next, i_next = (i_next + 1) % n_bufs)
325         {
326           if (b[i] == NULL)
327             b[i] = xmalloc (READ_BUFSIZE);
328           n_read = full_read (fd, b[i], READ_BUFSIZE);
329           if (n_read < READ_BUFSIZE)
330             {
331               if (errno != 0)
332                 {
333                   error (0, errno, _("error reading %s"), quote (filename));
334                   ok = false;
335                   goto free_mem;
336                 }
337               eof = true;
338             }
339
340           if (i + 1 == n_bufs)
341             buffered_enough = true;
342
343           if (buffered_enough)
344             {
345               if (fwrite (b[i_next], 1, n_read, stdout) < n_read)
346                 {
347                   error (0, errno, _("write error"));
348                   ok = false;
349                   goto free_mem;
350                 }
351             }
352         }
353
354       /* Output any remainder: rem bytes from b[i] + n_read.  */
355       if (rem)
356         {
357           if (buffered_enough)
358             {
359               size_t n_bytes_left_in_b_i = READ_BUFSIZE - n_read;
360               if (rem < n_bytes_left_in_b_i)
361                 {
362                   fwrite (b[i] + n_read, 1, rem, stdout);
363                 }
364               else
365                 {
366                   fwrite (b[i] + n_read, 1, n_bytes_left_in_b_i, stdout);
367                   fwrite (b[i_next], 1, rem - n_bytes_left_in_b_i, stdout);
368                 }
369             }
370           else if (i + 1 == n_bufs)
371             {
372               /* This happens when n_elide < file_size < n_elide_round.
373
374                  |READ_BUF.|
375                  |                      |  rem |
376                  |---------!---------!---------!---------|
377                  |---- n_elide ---------|
378                  |                      | x |
379                  |                   |y |
380                  |---- file size -----------|
381                  |                   |n_read|
382                  |---- n_elide_round ----------|
383                */
384               size_t y = READ_BUFSIZE - rem;
385               size_t x = n_read - y;
386               fwrite (b[i_next], 1, x, stdout);
387             }
388         }
389
390     free_mem:
391       for (i = 0; i < n_bufs; i++)
392         free (b[i]);
393       free (b);
394
395       return ok;
396     }
397 }
398
399 /* Print all but the last N_ELIDE lines from the input available
400    via file descriptor FD.  Return true upon success.
401    Give a diagnostic and return false upon error.  */
402
403 /* NOTE: if the input file shrinks by more than N_ELIDE bytes between
404    the length determination and the actual reading, then head fails.  */
405
406 static bool
407 elide_tail_bytes_file (const char *filename, int fd, uintmax_t n_elide)
408 {
409   struct stat stats;
410
411   if (presume_input_pipe || fstat (fd, &stats) || ! S_ISREG (stats.st_mode))
412     {
413       return elide_tail_bytes_pipe (filename, fd, n_elide);
414     }
415   else
416     {
417       off_t current_pos, end_pos;
418       uintmax_t bytes_remaining;
419       off_t diff;
420       enum Copy_fd_status err;
421
422       if ((current_pos = lseek (fd, 0, SEEK_CUR)) == -1
423           || (end_pos = lseek (fd, 0, SEEK_END)) == -1)
424         {
425           error (0, errno, _("cannot lseek %s"), quote (filename));
426           return false;
427         }
428
429       /* Be careful here.  The current position may actually be
430          beyond the end of the file.  */
431       bytes_remaining = (diff = end_pos - current_pos) < 0 ? 0 : diff;
432
433       if (bytes_remaining <= n_elide)
434         return true;
435
436       /* Seek back to 'current' position, then copy the required
437          number of bytes from fd.  */
438       if (lseek (fd, 0, current_pos) == -1)
439         {
440           error (0, errno, _("%s: cannot lseek back to original position"),
441                  quote (filename));
442           return false;
443         }
444
445       err = copy_fd (fd, stdout, bytes_remaining - n_elide);
446       if (err == COPY_FD_OK)
447         return true;
448
449       diagnose_copy_fd_failure (err, filename);
450       return false;
451     }
452 }
453
454 /* Print all but the last N_ELIDE lines from the input stream
455    open for reading via file descriptor FD.
456    Buffer the specified number of lines as a linked list of LBUFFERs,
457    adding them as needed.  Return true if successful.  */
458
459 static bool
460 elide_tail_lines_pipe (const char *filename, int fd, uintmax_t n_elide)
461 {
462   struct linebuffer
463   {
464     char buffer[BUFSIZ];
465     size_t nbytes;
466     size_t nlines;
467     struct linebuffer *next;
468   };
469   typedef struct linebuffer LBUFFER;
470   LBUFFER *first, *last, *tmp;
471   size_t total_lines = 0;       /* Total number of newlines in all buffers.  */
472   bool ok = true;
473   size_t n_read;                /* Size in bytes of most recent read */
474
475   first = last = xmalloc (sizeof (LBUFFER));
476   first->nbytes = first->nlines = 0;
477   first->next = NULL;
478   tmp = xmalloc (sizeof (LBUFFER));
479
480   /* Always read into a fresh buffer.
481      Read, (producing no output) until we've accumulated at least
482      n_elide newlines, or until EOF, whichever comes first.  */
483   while (1)
484     {
485       n_read = safe_read (fd, tmp->buffer, BUFSIZ);
486       if (n_read == 0 || n_read == SAFE_READ_ERROR)
487         break;
488       tmp->nbytes = n_read;
489       tmp->nlines = 0;
490       tmp->next = NULL;
491
492       /* Count the number of newlines just read.  */
493       {
494         char const *buffer_end = tmp->buffer + n_read;
495         char const *p = tmp->buffer;
496         while ((p = memchr (p, '\n', buffer_end - p)))
497           {
498             ++p;
499             ++tmp->nlines;
500           }
501       }
502       total_lines += tmp->nlines;
503
504       /* If there is enough room in the last buffer read, just append the new
505          one to it.  This is because when reading from a pipe, 'n_read' can
506          often be very small.  */
507       if (tmp->nbytes + last->nbytes < BUFSIZ)
508         {
509           memcpy (&last->buffer[last->nbytes], tmp->buffer, tmp->nbytes);
510           last->nbytes += tmp->nbytes;
511           last->nlines += tmp->nlines;
512         }
513       else
514         {
515           /* If there's not enough room, link the new buffer onto the end of
516              the list, then either free up the oldest buffer for the next
517              read if that would leave enough lines, or else malloc a new one.
518              Some compaction mechanism is possible but probably not
519              worthwhile.  */
520           last = last->next = tmp;
521           if (n_elide < total_lines - first->nlines)
522             {
523               fwrite (first->buffer, 1, first->nbytes, stdout);
524               tmp = first;
525               total_lines -= first->nlines;
526               first = first->next;
527             }
528           else
529             tmp = xmalloc (sizeof (LBUFFER));
530         }
531     }
532
533   free (tmp);
534
535   if (n_read == SAFE_READ_ERROR)
536     {
537       error (0, errno, _("error reading %s"), quote (filename));
538       ok = false;
539       goto free_lbuffers;
540     }
541
542   /* If we read any bytes at all, count the incomplete line
543      on files that don't end with a newline.  */
544   if (last->nbytes && last->buffer[last->nbytes - 1] != '\n')
545     {
546       ++last->nlines;
547       ++total_lines;
548     }
549
550   for (tmp = first; n_elide < total_lines - tmp->nlines; tmp = tmp->next)
551     {
552       fwrite (tmp->buffer, 1, tmp->nbytes, stdout);
553       total_lines -= tmp->nlines;
554     }
555
556   /* Print the first 'total_lines - n_elide' lines of tmp->buffer.  */
557   if (n_elide < total_lines)
558     {
559       size_t n = total_lines - n_elide;
560       char const *buffer_end = tmp->buffer + tmp->nbytes;
561       char const *p = tmp->buffer;
562       while (n && (p = memchr (p, '\n', buffer_end - p)))
563         {
564           ++p;
565           ++tmp->nlines;
566           --n;
567         }
568       fwrite (tmp->buffer, 1, p - tmp->buffer, stdout);
569     }
570
571 free_lbuffers:
572   while (first)
573     {
574       tmp = first->next;
575       free (first);
576       first = tmp;
577     }
578   return ok;
579 }
580
581 /* Output all but the last N_LINES lines of the input stream defined by
582    FD, START_POS, and END_POS.
583    START_POS is the starting position of the read pointer for the file
584    associated with FD (may be nonzero).
585    END_POS is the file offset of EOF (one larger than offset of last byte).
586    Return true upon success.
587    Give a diagnostic and return false upon error.
588
589    NOTE: this code is very similar to that of tail.c's file_lines function.
590    Unfortunately, factoring out some common core looks like it'd result
591    in a less efficient implementation or a messy interface.  */
592 static bool
593 elide_tail_lines_seekable (const char *pretty_filename, int fd,
594                            uintmax_t n_lines,
595                            off_t start_pos, off_t end_pos)
596 {
597   char buffer[BUFSIZ];
598   size_t bytes_read;
599   off_t pos = end_pos;
600
601   /* Set 'bytes_read' to the size of the last, probably partial, buffer;
602      0 < 'bytes_read' <= 'BUFSIZ'.  */
603   bytes_read = (pos - start_pos) % BUFSIZ;
604   if (bytes_read == 0)
605     bytes_read = BUFSIZ;
606   /* Make 'pos' a multiple of 'BUFSIZ' (0 if the file is short), so that all
607      reads will be on block boundaries, which might increase efficiency.  */
608   pos -= bytes_read;
609   if (lseek (fd, pos, SEEK_SET) < 0)
610     {
611       char offset_buf[INT_BUFSIZE_BOUND (pos)];
612       error (0, errno, _("%s: cannot seek to offset %s"),
613              pretty_filename, offtostr (pos, offset_buf));
614       return false;
615     }
616   bytes_read = safe_read (fd, buffer, bytes_read);
617   if (bytes_read == SAFE_READ_ERROR)
618     {
619       error (0, errno, _("error reading %s"), quote (pretty_filename));
620       return false;
621     }
622
623   /* Count the incomplete line on files that don't end with a newline.  */
624   if (bytes_read && buffer[bytes_read - 1] != '\n')
625     --n_lines;
626
627   while (1)
628     {
629       /* Scan backward, counting the newlines in this bufferfull.  */
630
631       size_t n = bytes_read;
632       while (n)
633         {
634           char const *nl;
635           nl = memrchr (buffer, '\n', n);
636           if (nl == NULL)
637             break;
638           n = nl - buffer;
639           if (n_lines-- == 0)
640             {
641               /* Found it.  */
642               /* If necessary, restore the file pointer and copy
643                  input to output up to position, POS.  */
644               if (start_pos < pos)
645                 {
646                   enum Copy_fd_status err;
647                   if (lseek (fd, start_pos, SEEK_SET) < 0)
648                     {
649                       /* Failed to reposition file pointer.  */
650                       error (0, errno,
651                          "%s: unable to restore file pointer to initial offset",
652                              quote (pretty_filename));
653                       return false;
654                     }
655
656                   err = copy_fd (fd, stdout, pos - start_pos);
657                   if (err != COPY_FD_OK)
658                     {
659                       diagnose_copy_fd_failure (err, pretty_filename);
660                       return false;
661                     }
662                 }
663
664               /* Output the initial portion of the buffer
665                  in which we found the desired newline byte.
666                  Don't bother testing for failure for such a small amount.
667                  Any failure will be detected upon close.  */
668               fwrite (buffer, 1, n + 1, stdout);
669
670               /* Set file pointer to the byte after what we've output.  */
671               if (lseek (fd, pos + n + 1, SEEK_SET) < 0)
672                 {
673                   error (0, errno, _("%s: failed to reset file pointer"),
674                          quote (pretty_filename));
675                   return false;
676                 }
677               return true;
678             }
679         }
680
681       /* Not enough newlines in that bufferfull.  */
682       if (pos == start_pos)
683         {
684           /* Not enough lines in the file.  */
685           return true;
686         }
687       pos -= BUFSIZ;
688       if (lseek (fd, pos, SEEK_SET) < 0)
689         {
690           char offset_buf[INT_BUFSIZE_BOUND (pos)];
691           error (0, errno, _("%s: cannot seek to offset %s"),
692                  pretty_filename, offtostr (pos, offset_buf));
693           return false;
694         }
695
696       bytes_read = safe_read (fd, buffer, BUFSIZ);
697       if (bytes_read == SAFE_READ_ERROR)
698         {
699           error (0, errno, _("error reading %s"), quote (pretty_filename));
700           return false;
701         }
702
703       /* FIXME: is this dead code?
704          Consider the test, pos == start_pos, above. */
705       if (bytes_read == 0)
706         return true;
707     }
708 }
709
710 /* Print all but the last N_ELIDE lines from the input available
711    via file descriptor FD.  Return true upon success.
712    Give a diagnostic and return nonzero upon error.  */
713
714 static bool
715 elide_tail_lines_file (const char *filename, int fd, uintmax_t n_elide)
716 {
717   if (!presume_input_pipe)
718     {
719       /* Find the offset, OFF, of the Nth newline from the end,
720          but not counting the last byte of the file.
721          If found, write from current position to OFF, inclusive.
722          Otherwise, just return true.  */
723
724       off_t start_pos = lseek (fd, 0, SEEK_CUR);
725       off_t end_pos = lseek (fd, 0, SEEK_END);
726       if (0 <= start_pos && start_pos < end_pos)
727         {
728           /* If the file is empty, we're done.  */
729           if (end_pos == 0)
730             return true;
731
732           return elide_tail_lines_seekable (filename, fd, n_elide,
733                                             start_pos, end_pos);
734         }
735
736       /* lseek failed or the end offset precedes start.
737          Fall through.  */
738     }
739
740   return elide_tail_lines_pipe (filename, fd, n_elide);
741 }
742
743 static bool
744 head_bytes (const char *filename, int fd, uintmax_t bytes_to_write)
745 {
746   char buffer[BUFSIZ];
747   size_t bytes_to_read = BUFSIZ;
748
749   while (bytes_to_write)
750     {
751       size_t bytes_read;
752       if (bytes_to_write < bytes_to_read)
753         bytes_to_read = bytes_to_write;
754       bytes_read = safe_read (fd, buffer, bytes_to_read);
755       if (bytes_read == SAFE_READ_ERROR)
756         {
757           error (0, errno, _("error reading %s"), quote (filename));
758           return false;
759         }
760       if (bytes_read == 0)
761         break;
762       if (fwrite (buffer, 1, bytes_read, stdout) < bytes_read)
763         error (EXIT_FAILURE, errno, _("write error"));
764       bytes_to_write -= bytes_read;
765     }
766   return true;
767 }
768
769 static bool
770 head_lines (const char *filename, int fd, uintmax_t lines_to_write)
771 {
772   char buffer[BUFSIZ];
773
774   while (lines_to_write)
775     {
776       size_t bytes_read = safe_read (fd, buffer, BUFSIZ);
777       size_t bytes_to_write = 0;
778
779       if (bytes_read == SAFE_READ_ERROR)
780         {
781           error (0, errno, _("error reading %s"), quote (filename));
782           return false;
783         }
784       if (bytes_read == 0)
785         break;
786       while (bytes_to_write < bytes_read)
787         if (buffer[bytes_to_write++] == '\n' && --lines_to_write == 0)
788           {
789             off_t n_bytes_past_EOL = bytes_read - bytes_to_write;
790             /* If we have read more data than that on the specified number
791                of lines, try to seek back to the position we would have
792                gotten to had we been reading one byte at a time.  */
793             if (lseek (fd, -n_bytes_past_EOL, SEEK_CUR) < 0)
794               {
795                 int e = errno;
796                 struct stat st;
797                 if (fstat (fd, &st) != 0 || S_ISREG (st.st_mode))
798                   error (0, e, _("cannot reposition file pointer for %s"),
799                          quote (filename));
800               }
801             break;
802           }
803       if (fwrite (buffer, 1, bytes_to_write, stdout) < bytes_to_write)
804         error (EXIT_FAILURE, errno, _("write error"));
805     }
806   return true;
807 }
808
809 static bool
810 head (const char *filename, int fd, uintmax_t n_units, bool count_lines,
811       bool elide_from_end)
812 {
813   if (print_headers)
814     write_header (filename);
815
816   if (elide_from_end)
817     {
818       if (count_lines)
819         {
820           return elide_tail_lines_file (filename, fd, n_units);
821         }
822       else
823         {
824           return elide_tail_bytes_file (filename, fd, n_units);
825         }
826     }
827   if (count_lines)
828     return head_lines (filename, fd, n_units);
829   else
830     return head_bytes (filename, fd, n_units);
831 }
832
833 static bool
834 head_file (const char *filename, uintmax_t n_units, bool count_lines,
835            bool elide_from_end)
836 {
837   int fd;
838   bool ok;
839   bool is_stdin = STREQ (filename, "-");
840
841   if (is_stdin)
842     {
843       have_read_stdin = true;
844       fd = STDIN_FILENO;
845       filename = _("standard input");
846       if (O_BINARY && ! isatty (STDIN_FILENO))
847         xfreopen (NULL, "rb", stdin);
848     }
849   else
850     {
851       fd = open (filename, O_RDONLY | O_BINARY);
852       if (fd < 0)
853         {
854           error (0, errno, _("cannot open %s for reading"), quote (filename));
855           return false;
856         }
857     }
858
859   ok = head (filename, fd, n_units, count_lines, elide_from_end);
860   if (!is_stdin && close (fd) != 0)
861     {
862       error (0, errno, _("failed to close %s"), quote (filename));
863       return false;
864     }
865   return ok;
866 }
867
868 /* Convert a string of decimal digits, N_STRING, with an optional suffinx
869    to an integral value.  Upon successful conversion,
870    return that value.  If it cannot be converted, give a diagnostic and exit.
871    COUNT_LINES indicates whether N_STRING is a number of bytes or a number
872    of lines.  It is used solely to give a more specific diagnostic.  */
873
874 static uintmax_t
875 string_to_integer (bool count_lines, const char *n_string)
876 {
877   strtol_error s_err;
878   uintmax_t n;
879
880   s_err = xstrtoumax (n_string, NULL, 10, &n, "bkKmMGTPEZY0");
881
882   if (s_err == LONGINT_OVERFLOW)
883     {
884       error (EXIT_FAILURE, 0,
885              _("%s: %s is so large that it is not representable"), n_string,
886              count_lines ? _("number of lines") : _("number of bytes"));
887     }
888
889   if (s_err != LONGINT_OK)
890     {
891       error (EXIT_FAILURE, 0, "%s: %s", n_string,
892              (count_lines
893               ? _("invalid number of lines")
894               : _("invalid number of bytes")));
895     }
896
897   return n;
898 }
899
900 int
901 main (int argc, char **argv)
902 {
903   enum header_mode header_mode = multiple_files;
904   bool ok = true;
905   int c;
906   size_t i;
907
908   /* Number of items to print. */
909   uintmax_t n_units = DEFAULT_NUMBER;
910
911   /* If true, interpret the numeric argument as the number of lines.
912      Otherwise, interpret it as the number of bytes.  */
913   bool count_lines = true;
914
915   /* Elide the specified number of lines or bytes, counting from
916      the end of the file.  */
917   bool elide_from_end = false;
918
919   /* Initializer for file_list if no file-arguments
920      were specified on the command line.  */
921   static char const *const default_file_list[] = {"-", NULL};
922   char const *const *file_list;
923
924   initialize_main (&argc, &argv);
925   set_program_name (argv[0]);
926   setlocale (LC_ALL, "");
927   bindtextdomain (PACKAGE, LOCALEDIR);
928   textdomain (PACKAGE);
929
930   atexit (close_stdout);
931
932   have_read_stdin = false;
933
934   print_headers = false;
935
936   if (1 < argc && argv[1][0] == '-' && ISDIGIT (argv[1][1]))
937     {
938       char *a = argv[1];
939       char *n_string = ++a;
940       char *end_n_string;
941       char multiplier_char = 0;
942
943       /* Old option syntax; a dash, one or more digits, and one or
944          more option letters.  Move past the number. */
945       do ++a;
946       while (ISDIGIT (*a));
947
948       /* Pointer to the byte after the last digit.  */
949       end_n_string = a;
950
951       /* Parse any appended option letters. */
952       for (; *a; a++)
953         {
954           switch (*a)
955             {
956             case 'c':
957               count_lines = false;
958               multiplier_char = 0;
959               break;
960
961             case 'b':
962             case 'k':
963             case 'm':
964               count_lines = false;
965               multiplier_char = *a;
966               break;
967
968             case 'l':
969               count_lines = true;
970               break;
971
972             case 'q':
973               header_mode = never;
974               break;
975
976             case 'v':
977               header_mode = always;
978               break;
979
980             default:
981               error (0, 0, _("invalid trailing option -- %c"), *a);
982               usage (EXIT_FAILURE);
983             }
984         }
985
986       /* Append the multiplier character (if any) onto the end of
987          the digit string.  Then add NUL byte if necessary.  */
988       *end_n_string = multiplier_char;
989       if (multiplier_char)
990         *(++end_n_string) = 0;
991
992       n_units = string_to_integer (count_lines, n_string);
993
994       /* Make the options we just parsed invisible to getopt. */
995       argv[1] = argv[0];
996       argv++;
997       argc--;
998     }
999
1000   while ((c = getopt_long (argc, argv, "c:n:qv0123456789", long_options, NULL))
1001          != -1)
1002     {
1003       switch (c)
1004         {
1005         case PRESUME_INPUT_PIPE_OPTION:
1006           presume_input_pipe = true;
1007           break;
1008
1009         case 'c':
1010           count_lines = false;
1011           elide_from_end = (*optarg == '-');
1012           if (elide_from_end)
1013             ++optarg;
1014           n_units = string_to_integer (count_lines, optarg);
1015           break;
1016
1017         case 'n':
1018           count_lines = true;
1019           elide_from_end = (*optarg == '-');
1020           if (elide_from_end)
1021             ++optarg;
1022           n_units = string_to_integer (count_lines, optarg);
1023           break;
1024
1025         case 'q':
1026           header_mode = never;
1027           break;
1028
1029         case 'v':
1030           header_mode = always;
1031           break;
1032
1033         case_GETOPT_HELP_CHAR;
1034
1035         case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
1036
1037         default:
1038           if (ISDIGIT (c))
1039             error (0, 0, _("invalid trailing option -- %c"), c);
1040           usage (EXIT_FAILURE);
1041         }
1042     }
1043
1044   if (header_mode == always
1045       || (header_mode == multiple_files && optind < argc - 1))
1046     print_headers = true;
1047
1048   if ( ! count_lines && elide_from_end && OFF_T_MAX < n_units)
1049     {
1050       char umax_buf[INT_BUFSIZE_BOUND (n_units)];
1051       error (EXIT_FAILURE, 0, _("%s: number of bytes is too large"),
1052              umaxtostr (n_units, umax_buf));
1053     }
1054
1055   file_list = (optind < argc
1056                ? (char const *const *) &argv[optind]
1057                : default_file_list);
1058
1059   if (O_BINARY && ! isatty (STDOUT_FILENO))
1060     xfreopen (NULL, "wb", stdout);
1061
1062   for (i = 0; file_list[i]; ++i)
1063     ok &= head_file (file_list[i], n_units, count_lines, elide_from_end);
1064
1065   if (have_read_stdin && close (STDIN_FILENO) < 0)
1066     error (EXIT_FAILURE, errno, "-");
1067
1068   exit (ok ? EXIT_SUCCESS : EXIT_FAILURE);
1069 }