1 /* vi: set sw=4 ts=4: */
3 * head implementation for busybox
5 * Copyright (C) 2003 Manuel Novoa III <mjn3@codepoet.org>
7 * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
10 /* BB_AUDIT SUSv3 compliant */
11 /* BB_AUDIT GNU compatible -c, -q, and -v options in 'fancy' configuration. */
12 /* http://www.opengroup.org/onlinepubs/007904975/utilities/head.html */
16 static const char head_opts
[] ALIGN1
=
18 #if ENABLE_FEATURE_FANCY_HEAD
23 #if ENABLE_FEATURE_FANCY_HEAD
24 static const struct suffix_mult head_suffixes
[] = {
32 static const char header_fmt_str
[] ALIGN1
= "\n==> %s <==\n";
34 int head_main(int argc
, char **argv
) MAIN_EXTERNALLY_VISIBLE
;
35 int head_main(int argc
, char **argv
)
37 unsigned long count
= 10;
39 #if ENABLE_FEATURE_FANCY_HEAD
41 int header_threshhold
= 1;
48 int retval
= EXIT_SUCCESS
;
50 #if ENABLE_INCLUDE_SUSv2 || ENABLE_FEATURE_FANCY_HEAD
51 /* Allow legacy syntax of an initial numeric option without -n. */
52 if (argv
[1] && argv
[1][0] == '-'
53 && isdigit(argv
[1][1])
62 /* No size benefit in converting this to getopt32 */
63 while ((opt
= getopt(argc
, argv
, head_opts
)) > 0) {
65 #if ENABLE_FEATURE_FANCY_HEAD
67 header_threshhold
= INT_MAX
;
70 header_threshhold
= -1;
78 #if ENABLE_INCLUDE_SUSv2 || ENABLE_FEATURE_FANCY_HEAD
81 #if !ENABLE_FEATURE_FANCY_HEAD
84 count
= xatoul_sfx(p
, head_suffixes
);
97 fmt
= header_fmt_str
+ 1;
98 #if ENABLE_FEATURE_FANCY_HEAD
99 if (argc
<= header_threshhold
) {
100 header_threshhold
= 0;
106 /* Now define some things here to avoid #ifdefs in the code below.
107 * These should optimize out of the if conditions below. */
108 #define header_threshhold 1
109 #define count_bytes 0
113 fp
= fopen_or_warn_stdin(*argv
);
116 *argv
= (char *) bb_msg_standard_input
;
118 if (header_threshhold
) {
122 while (i
&& ((c
= getc(fp
)) != EOF
)) {
123 if (count_bytes
|| (c
== '\n')) {
128 if (fclose_if_not_stdin(fp
)) {
129 bb_simple_perror_msg(*argv
);
130 retval
= EXIT_FAILURE
;
132 die_if_ferror_stdout();
134 retval
= EXIT_FAILURE
;
136 fmt
= header_fmt_str
;
139 fflush_stdout_and_exit(retval
);