1 /* vi: set sw=4 ts=4: */
3 * head implementation for busybox
5 * Copyright (C) 2003 Manuel Novoa III <mjn3@codepoet.org>
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23 /* BB_AUDIT SUSv3 compliant */
24 /* BB_AUDIT GNU compatible -c, -q, and -v options in 'fancy' configuration. */
25 /* http://www.opengroup.org/onlinepubs/007904975/utilities/head.html */
34 static const char head_opts[] =
36 #if ENABLE_FEATURE_FANCY_HEAD
41 static const char header_fmt_str[] = "\n==> %s <==\n";
43 int head_main(int argc, char **argv)
45 unsigned long count = 10;
47 #if ENABLE_FEATURE_FANCY_HEAD
49 int header_threshhold = 1;
57 int retval = EXIT_SUCCESS;
59 #if defined CONFIG_FEATURE_SUSv2 || ENABLE_FEATURE_FANCY_HEAD
60 /* Allow legacy syntax of an initial numeric option without -n. */
61 if ((argc > 1) && (argv[1][0] == '-')
62 /* && (isdigit)(argv[1][1]) */
63 && (((unsigned int)(argv[1][1] - '0')) <= 9)
72 /* No size benefit in converting this to bb_getopt_ulflags */
73 while ((opt = getopt(argc, argv, head_opts)) > 0) {
75 #if ENABLE_FEATURE_FANCY_HEAD
77 header_threshhold = INT_MAX;
80 header_threshhold = -1;
88 #if defined CONFIG_FEATURE_SUSv2 || ENABLE_FEATURE_FANCY_HEAD
91 count = bb_xgetularg10(p);
103 fmt = header_fmt_str + 1;
104 #if ENABLE_FEATURE_FANCY_HEAD
105 if (argc - optind <= header_threshhold) {
106 header_threshhold = 0;
109 if (argc <= optind + 1) {
112 /* Now define some things here to avoid #ifdefs in the code below.
113 * These should optimize out of the if conditions below. */
114 #define header_threshhold 1
115 #define count_bytes 0
119 if ((fp = bb_wfopen_input(*argv)) != NULL) {
121 *argv = (char *) bb_msg_standard_input;
123 if (header_threshhold) {
124 bb_printf(fmt, *argv);
127 while (i && ((c = getc(fp)) != EOF)) {
128 if (count_bytes || (c == '\n')) {
133 if (bb_fclose_nonstdin(fp)) {
134 bb_perror_msg("%s", *argv); /* Avoid multibyte problems. */
135 retval = EXIT_FAILURE;
139 fmt = header_fmt_str;
142 bb_fflush_stdout_and_exit(retval);