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 static const struct suffix_mult head_suffixes[] = {
30 #define header_fmt_str "\n==> %s <==\n"
32 int head_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
33 int head_main(int argc, char **argv)
35 unsigned long count = 10;
37 #if ENABLE_FEATURE_FANCY_HEAD
39 int header_threshhold = 1;
46 int retval = EXIT_SUCCESS;
48 #if ENABLE_INCLUDE_SUSv2 || ENABLE_FEATURE_FANCY_HEAD
49 /* Allow legacy syntax of an initial numeric option without -n. */
50 if (argv[1] && argv[1][0] == '-'
51 && isdigit(argv[1][1])
60 /* No size benefit in converting this to getopt32 */
61 while ((opt = getopt(argc, argv, head_opts)) > 0) {
63 #if ENABLE_FEATURE_FANCY_HEAD
65 header_threshhold = INT_MAX;
68 header_threshhold = -1;
76 #if ENABLE_INCLUDE_SUSv2 || ENABLE_FEATURE_FANCY_HEAD
79 count = xatoul_sfx(p, head_suffixes);
91 fmt = header_fmt_str + 1;
92 #if ENABLE_FEATURE_FANCY_HEAD
93 if (argc <= header_threshhold) {
94 header_threshhold = 0;
100 /* Now define some things here to avoid #ifdefs in the code below.
101 * These should optimize out of the if conditions below. */
102 #define header_threshhold 1
103 #define count_bytes 0
107 fp = fopen_or_warn_stdin(*argv);
110 *argv = (char *) bb_msg_standard_input;
112 if (header_threshhold) {
116 while (i && ((c = getc(fp)) != EOF)) {
117 if (count_bytes || (c == '\n')) {
122 if (fclose_if_not_stdin(fp)) {
123 bb_simple_perror_msg(*argv);
124 retval = EXIT_FAILURE;
126 die_if_ferror_stdout();
128 retval = EXIT_FAILURE;
130 fmt = header_fmt_str;
133 fflush_stdout_and_exit(retval);