1 /* head -- output first part of file(s)
2 Copyright (C) 89, 90, 91, 1995-2002 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>
37 #include "safe-read.h"
39 /* The official name of this program (e.g., no `g' prefix). */
40 #define PROGRAM_NAME "head"
42 #define AUTHORS "David MacKenzie"
44 /* Number of lines/chars/blocks to head. */
45 #define DEFAULT_NUMBER 10
47 /* Size of atomic reads. */
48 #define BUFSIZE (512 * 8)
50 /* If nonzero, print filename headers. */
51 static int print_headers
;
53 /* When to print the filename banners. */
56 multiple_files
, always
, never
59 /* Options corresponding to header_mode values. */
60 static char const header_mode_option
[][4] = { "", " -v", " -q" };
62 /* The name this program was run with. */
65 /* Have we ever read standard input? */
66 static int have_read_stdin
;
68 static struct option
const long_options
[] =
70 {"bytes", required_argument
, NULL
, 'c'},
71 {"lines", required_argument
, NULL
, 'n'},
72 {"quiet", no_argument
, NULL
, 'q'},
73 {"silent", no_argument
, NULL
, 'q'},
74 {"verbose", no_argument
, NULL
, 'v'},
75 {GETOPT_HELP_OPTION_DECL
},
76 {GETOPT_VERSION_OPTION_DECL
},
84 fprintf (stderr
, _("Try `%s --help' for more information.\n"),
89 Usage: %s [OPTION]... [FILE]...\n\
93 Print first 10 lines of each FILE to standard output.\n\
94 With more than one FILE, precede each with a header giving the file name.\n\
95 With no FILE, or when FILE is -, read standard input.\n\
99 Mandatory arguments to long options are mandatory for short options too.\n\
102 -c, --bytes=SIZE print first SIZE bytes\n\
103 -n, --lines=NUMBER print first NUMBER lines instead of first 10\n\
106 -q, --quiet, --silent never print headers giving file names\n\
107 -v, --verbose always print headers giving file names\n\
109 fputs (HELP_OPTION_DESCRIPTION
, stdout
);
110 fputs (VERSION_OPTION_DESCRIPTION
, stdout
);
113 SIZE may have a multiplier suffix: b for 512, k for 1K, m for 1 Meg.\n\
115 printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT
);
117 exit (status
== 0 ? EXIT_SUCCESS
: EXIT_FAILURE
);
121 write_header (const char *filename
)
123 static int first_file
= 1;
125 printf ("%s==> %s <==\n", (first_file
? "" : "\n"), filename
);
130 head_bytes (const char *filename
, int fd
, uintmax_t bytes_to_write
)
132 char buffer
[BUFSIZE
];
134 size_t bytes_to_read
= BUFSIZE
;
136 /* Need BINARY I/O for the byte counts to be accurate. */
137 SET_BINARY2 (fd
, fileno (stdout
));
139 while (bytes_to_write
)
141 if (bytes_to_write
< bytes_to_read
)
142 bytes_to_read
= bytes_to_write
;
143 bytes_read
= safe_read (fd
, buffer
, bytes_to_read
);
146 error (0, errno
, "%s", filename
);
151 if (fwrite (buffer
, 1, bytes_read
, stdout
) == 0)
152 error (EXIT_FAILURE
, errno
, _("write error"));
153 bytes_to_write
-= bytes_read
;
159 head_lines (const char *filename
, int fd
, uintmax_t lines_to_write
)
161 char buffer
[BUFSIZE
];
163 /* Need BINARY I/O for the byte counts to be accurate. */
164 SET_BINARY2 (fd
, fileno (stdout
));
166 while (lines_to_write
)
168 int bytes_read
= safe_read (fd
, buffer
, BUFSIZE
);
169 int bytes_to_write
= 0;
173 error (0, errno
, "%s", filename
);
178 while (bytes_to_write
< bytes_read
)
179 if (buffer
[bytes_to_write
++] == '\n' && --lines_to_write
== 0)
181 /* If we have read more data than that on the specified number
182 of lines, try to seek back to the position we would have
183 gotten to had we been reading one byte at a time. */
184 if (lseek (fd
, bytes_to_write
- bytes_read
, SEEK_CUR
) < 0)
188 if (fstat (fd
, &st
) != 0 || S_ISREG (st
.st_mode
))
189 error (0, e
, _("cannot reposition file pointer for %s"),
194 if (fwrite (buffer
, 1, bytes_to_write
, stdout
) == 0)
195 error (EXIT_FAILURE
, errno
, _("write error"));
201 head (const char *filename
, int fd
, uintmax_t n_units
, int count_lines
)
204 write_header (filename
);
207 return head_lines (filename
, fd
, n_units
);
209 return head_bytes (filename
, fd
, n_units
);
213 head_file (const char *filename
, uintmax_t n_units
, int count_lines
)
217 if (STREQ (filename
, "-"))
220 return head (_("standard input"), STDIN_FILENO
, n_units
, count_lines
);
224 fd
= open (filename
, O_RDONLY
);
229 errors
= head (filename
, fd
, n_units
, count_lines
);
233 error (0, errno
, "%s", filename
);
238 /* Convert a string of decimal digits, N_STRING, with a single, optional suffix
239 character (b, k, or m) to an integral value. Upon successful conversion,
240 return that value. If it cannot be converted, give a diagnostic and exit.
241 COUNT_LINES indicates whether N_STRING is a number of bytes or a number
242 of lines. It is used solely to give a more specific diagnostic. */
245 string_to_integer (int count_lines
, const char *n_string
)
250 s_err
= xstrtoumax (n_string
, NULL
, 10, &n
, "bkm");
252 if (s_err
== LONGINT_OVERFLOW
)
254 error (EXIT_FAILURE
, 0,
255 _("%s: %s is so large that it is not representable"), n_string
,
256 count_lines
? _("number of lines") : _("number of bytes"));
259 if (s_err
!= LONGINT_OK
)
261 error (EXIT_FAILURE
, 0, "%s: %s", n_string
,
263 ? _("invalid number of lines")
264 : _("invalid number of bytes")));
271 main (int argc
, char **argv
)
273 enum header_mode header_mode
= multiple_files
;
277 /* Number of items to print. */
278 uintmax_t n_units
= DEFAULT_NUMBER
;
280 /* If nonzero, interpret the numeric argument as the number of lines.
281 Otherwise, interpret it as the number of bytes. */
284 program_name
= argv
[0];
285 setlocale (LC_ALL
, "");
286 bindtextdomain (PACKAGE
, LOCALEDIR
);
287 textdomain (PACKAGE
);
289 atexit (close_stdout
);
295 if (1 < argc
&& argv
[1][0] == '-' && ISDIGIT (argv
[1][1]))
298 char *n_string
= ++a
;
300 char multiplier_char
= 0;
302 /* Old option syntax; a dash, one or more digits, and one or
303 more option letters. Move past the number. */
305 while (ISDIGIT (*a
));
307 /* Pointer to the byte after the last digit. */
310 /* Parse any appended option letters. */
324 multiplier_char
= *a
;
336 header_mode
= always
;
340 error (0, 0, _("unrecognized option `-%c'"), *a
);
345 if (200112 <= posix2_version ())
347 error (0, 0, _("`-%s' option is obsolete; use `-%c %.*s%.*s%s'"),
348 n_string
, count_lines
? 'n' : 'c',
349 (int) (end_n_string
- n_string
), n_string
,
350 multiplier_char
!= 0, &multiplier_char
,
351 header_mode_option
[header_mode
]);
352 usage (EXIT_FAILURE
);
355 /* Append the multiplier character (if any) onto the end of
356 the digit string. Then add NUL byte if necessary. */
357 *end_n_string
= multiplier_char
;
359 *(++end_n_string
) = 0;
361 n_units
= string_to_integer (count_lines
, n_string
);
363 /* Make the options we just parsed invisible to getopt. */
368 /* FIXME: allow POSIX options if there were obsolescent ones? */
372 while ((c
= getopt_long (argc
, argv
, "c:n:qv", long_options
, NULL
)) != -1)
381 n_units
= string_to_integer (count_lines
, optarg
);
386 n_units
= string_to_integer (count_lines
, optarg
);
394 header_mode
= always
;
397 case_GETOPT_HELP_CHAR
;
399 case_GETOPT_VERSION_CHAR (PROGRAM_NAME
, AUTHORS
);
406 if (header_mode
== always
407 || (header_mode
== multiple_files
&& optind
< argc
- 1))
411 exit_status
|= head_file ("-", n_units
, count_lines
);
413 for (; optind
< argc
; ++optind
)
414 exit_status
|= head_file (argv
[optind
], n_units
, count_lines
);
416 if (have_read_stdin
&& close (STDIN_FILENO
) < 0)
417 error (EXIT_FAILURE
, errno
, "-");
419 exit (exit_status
== 0 ? EXIT_SUCCESS
: EXIT_FAILURE
);