176e91e3aa0b556aa21a650d49b82cef6a1018f8
[oweals/busybox.git] / coreutils / head.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * head implementation for busybox
4  *
5  * Copyright (C) 2003  Manuel Novoa III  <mjn3@codepoet.org>
6  *
7  * Licensed under GPLv2 or later, see file LICENSE in this source tree.
8  */
9 //config:config HEAD
10 //config:       bool "head"
11 //config:       default y
12 //config:       help
13 //config:         head is used to print the first specified number of lines
14 //config:         from files.
15 //config:
16 //config:config FEATURE_FANCY_HEAD
17 //config:       bool "Enable head options (-c, -q, and -v)"
18 //config:       default y
19 //config:       depends on HEAD
20 //config:       help
21 //config:         This enables the head options (-c, -q, and -v).
22
23 //applet:IF_HEAD(APPLET_NOEXEC(head, head, BB_DIR_USR_BIN, BB_SUID_DROP, head))
24
25 //kbuild:lib-$(CONFIG_HEAD) += head.o
26
27 /* BB_AUDIT SUSv3 compliant */
28 /* BB_AUDIT GNU compatible -c, -q, and -v options in 'fancy' configuration. */
29 /* http://www.opengroup.org/onlinepubs/007904975/utilities/head.html */
30
31 //usage:#define head_trivial_usage
32 //usage:       "[OPTIONS] [FILE]..."
33 //usage:#define head_full_usage "\n\n"
34 //usage:       "Print first 10 lines of each FILE (or stdin) to stdout.\n"
35 //usage:       "With more than one FILE, precede each with a filename header.\n"
36 //usage:     "\n        -n N[kbm]       Print first N lines"
37 //usage:        IF_FEATURE_FANCY_HEAD(
38 //usage:     "\n        -n -N[kbm]      Print all except N last lines"
39 //usage:     "\n        -c [-]N[kbm]    Print first N bytes"
40 //usage:     "\n        -q              Never print headers"
41 //usage:     "\n        -v              Always print headers"
42 //usage:        )
43 //usage:     "\n"
44 //usage:     "\nN may be suffixed by k (x1024), b (x512), or m (x1024^2)."
45 //usage:
46 //usage:#define head_example_usage
47 //usage:       "$ head -n 2 /etc/passwd\n"
48 //usage:       "root:x:0:0:root:/root:/bin/bash\n"
49 //usage:       "daemon:x:1:1:daemon:/usr/sbin:/bin/sh\n"
50
51 #include "libbb.h"
52
53 /* This is a NOEXEC applet. Be very careful! */
54
55 #if !ENABLE_FEATURE_FANCY_HEAD
56 # define print_first_N(fp,count,bytes) print_first_N(fp,count)
57 #endif
58 static void
59 print_first_N(FILE *fp, unsigned long count, bool count_bytes)
60 {
61 #if !ENABLE_FEATURE_FANCY_HEAD
62         const int count_bytes = 0;
63 #endif
64         while (count) {
65                 int c = getc(fp);
66                 if (c == EOF)
67                         break;
68                 if (count_bytes || (c == '\n'))
69                         --count;
70                 putchar(c);
71         }
72 }
73
74 #if ENABLE_FEATURE_FANCY_HEAD
75 static void
76 print_except_N_last_bytes(FILE *fp, unsigned count)
77 {
78         unsigned char *circle = xmalloc(++count);
79         unsigned head = 0;
80         for(;;) {
81                 int c;
82                 c = getc(fp);
83                 if (c == EOF)
84                         goto ret;
85                 circle[head++] = c;
86                 if (head == count)
87                         break;
88         }
89         for (;;) {
90                 int c;
91                 if (head == count)
92                         head = 0;
93                 putchar(circle[head]);
94                 c = getc(fp);
95                 if (c == EOF)
96                         goto ret;
97                 circle[head] = c;
98                 head++;
99         }
100  ret:
101         free(circle);
102 }
103
104 static void
105 print_except_N_last_lines(FILE *fp, unsigned count)
106 {
107         char **circle = xzalloc((++count) * sizeof(circle[0]));
108         unsigned head = 0;
109         for(;;) {
110                 char *c;
111                 c = xmalloc_fgets(fp);
112                 if (!c)
113                         goto ret;
114                 circle[head++] = c;
115                 if (head == count)
116                         break;
117         }
118         for (;;) {
119                 char *c;
120                 if (head == count)
121                         head = 0;
122                 fputs(circle[head], stdout);
123                 c = xmalloc_fgets(fp);
124                 if (!c)
125                         goto ret;
126                 free(circle[head]);
127                 circle[head++] = c;
128         }
129  ret:
130         head = 0;
131         for(;;) {
132                 free(circle[head++]);
133                 if (head == count)
134                         break;
135         }
136         free(circle);
137 }
138 #else
139 /* Must never be called */
140 void print_except_N_last_bytes(FILE *fp, unsigned count);
141 void print_except_N_last_lines(FILE *fp, unsigned count);
142 #endif
143
144 #if !ENABLE_FEATURE_FANCY_HEAD
145 # define eat_num(negative_N,p) eat_num(p)
146 #endif
147 static unsigned long
148 eat_num(bool *negative_N, const char *p)
149 {
150 #if ENABLE_FEATURE_FANCY_HEAD
151         if (*p == '-') {
152                 *negative_N = 1;
153                 p++;
154         }
155 #endif
156         return xatoul_sfx(p, bkm_suffixes);
157 }
158
159 static const char head_opts[] ALIGN1 =
160         "n:"
161 #if ENABLE_FEATURE_FANCY_HEAD
162         "c:qv"
163 #endif
164         ;
165
166 #define header_fmt_str "\n==> %s <==\n"
167
168 int head_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
169 int head_main(int argc, char **argv)
170 {
171         unsigned long count = 10;
172 #if ENABLE_FEATURE_FANCY_HEAD
173         int header_threshhold = 1;
174         bool count_bytes = 0;
175         bool negative_N = 0;
176 #else
177 # define header_threshhold 1
178 # define count_bytes       0
179 # define negative_N        0
180 #endif
181         FILE *fp;
182         const char *fmt;
183         char *p;
184         int opt;
185         int retval = EXIT_SUCCESS;
186
187 #if ENABLE_INCLUDE_SUSv2 || ENABLE_FEATURE_FANCY_HEAD
188         /* Allow legacy syntax of an initial numeric option without -n. */
189         if (argv[1] && argv[1][0] == '-'
190          && isdigit(argv[1][1])
191         ) {
192                 --argc;
193                 ++argv;
194                 p = argv[0] + 1;
195                 goto GET_COUNT;
196         }
197 #endif
198
199         /* No size benefit in converting this to getopt32 */
200         while ((opt = getopt(argc, argv, head_opts)) > 0) {
201                 switch (opt) {
202 #if ENABLE_FEATURE_FANCY_HEAD
203                 case 'q':
204                         header_threshhold = INT_MAX;
205                         break;
206                 case 'v':
207                         header_threshhold = -1;
208                         break;
209                 case 'c':
210                         count_bytes = 1;
211                         /* fall through */
212 #endif
213                 case 'n':
214                         p = optarg;
215 #if ENABLE_INCLUDE_SUSv2 || ENABLE_FEATURE_FANCY_HEAD
216  GET_COUNT:
217 #endif
218                         count = eat_num(&negative_N, p);
219                         break;
220                 default:
221                         bb_show_usage();
222                 }
223         }
224
225         argc -= optind;
226         argv += optind;
227         if (!*argv)
228                 *--argv = (char*)"-";
229
230         fmt = header_fmt_str + 1;
231         if (argc <= header_threshhold) {
232 #if ENABLE_FEATURE_FANCY_HEAD
233                 header_threshhold = 0;
234 #else
235                 fmt += 11; /* "" */
236 #endif
237         }
238         if (negative_N) {
239                 if (count >= INT_MAX / sizeof(char*))
240                         bb_error_msg("count is too big: %lu", count);
241         }
242
243         do {
244                 fp = fopen_or_warn_stdin(*argv);
245                 if (fp) {
246                         if (fp == stdin) {
247                                 *argv = (char *) bb_msg_standard_input;
248                         }
249                         if (header_threshhold) {
250                                 printf(fmt, *argv);
251                         }
252                         if (negative_N) {
253                                 if (count_bytes) {
254                                         print_except_N_last_bytes(fp, count);
255                                 } else {
256                                         print_except_N_last_lines(fp, count);
257                                 }
258                         } else {
259                                 print_first_N(fp, count, count_bytes);
260                         }
261                         die_if_ferror_stdout();
262                         if (fclose_if_not_stdin(fp)) {
263                                 bb_simple_perror_msg(*argv);
264                                 retval = EXIT_FAILURE;
265                         }
266                 } else {
267                         retval = EXIT_FAILURE;
268                 }
269                 fmt = header_fmt_str;
270         } while (*++argv);
271
272         fflush_stdout_and_exit(retval);
273 }