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 */
21 static const char head_opts[] =
23 #if ENABLE_FEATURE_FANCY_HEAD
28 #if ENABLE_FEATURE_FANCY_HEAD
29 static const struct suffix_mult head_suffixes[] = {
37 static const char header_fmt_str[] = "\n==> %s <==\n";
39 int head_main(int argc, char **argv)
41 unsigned long count = 10;
43 #if ENABLE_FEATURE_FANCY_HEAD
45 int header_threshhold = 1;
53 int retval = EXIT_SUCCESS;
55 #if !ENABLE_DEBUG_YANK_SUSv2 || ENABLE_FEATURE_FANCY_HEAD
56 /* Allow legacy syntax of an initial numeric option without -n. */
57 if ((argc > 1) && (argv[1][0] == '-')
58 /* && (isdigit)(argv[1][1]) */
59 && (((unsigned int)(argv[1][1] - '0')) <= 9)
68 /* No size benefit in converting this to bb_getopt_ulflags */
69 while ((opt = getopt(argc, argv, head_opts)) > 0) {
71 #if ENABLE_FEATURE_FANCY_HEAD
73 header_threshhold = INT_MAX;
76 header_threshhold = -1;
84 #if !ENABLE_DEBUG_YANK_SUSv2 || ENABLE_FEATURE_FANCY_HEAD
88 #if !ENABLE_FEATURE_FANCY_HEAD
89 count = bb_xgetularg10(p);
91 count = bb_xgetularg_bnd_sfx(p, 10,
106 fmt = header_fmt_str + 1;
107 #if ENABLE_FEATURE_FANCY_HEAD
108 if (argc - optind <= header_threshhold) {
109 header_threshhold = 0;
112 if (argc <= optind + 1) {
115 /* Now define some things here to avoid #ifdefs in the code below.
116 * These should optimize out of the if conditions below. */
117 #define header_threshhold 1
118 #define count_bytes 0
122 if ((fp = bb_wfopen_input(*argv)) != NULL) {
124 *argv = (char *) bb_msg_standard_input;
126 if (header_threshhold) {
127 bb_printf(fmt, *argv);
130 while (i && ((c = getc(fp)) != EOF)) {
131 if (count_bytes || (c == '\n')) {
136 if (bb_fclose_nonstdin(fp)) {
137 bb_perror_msg("%s", *argv); /* Avoid multibyte problems. */
138 retval = EXIT_FAILURE;
142 fmt = header_fmt_str;
145 bb_fflush_stdout_and_exit(retval);