444
|
1 /* vi: set sw=4 ts=4:
|
|
2 *
|
|
3 * head.c - copy first lines from input to stdout.
|
|
4 *
|
|
5 * Copyright 2006 Timothy Elliott <tle@holymonkey.com>
|
|
6 *
|
|
7 * See http://www.opengroup.org/onlinepubs/009695399/utilities/head.html
|
|
8
|
445
|
9 USE_HEAD(NEWTOY(head, "n#<0=10", TOYFLAG_BIN))
|
444
|
10
|
|
11 config HEAD
|
|
12 bool "head"
|
|
13 default y
|
|
14 help
|
|
15 usage: head [-n number] [file...]
|
445
|
16
|
444
|
17 Copy first lines from files to stdout. If no files listed, copy from
|
|
18 stdin. Filename "-" is a synonym for stdin.
|
|
19
|
|
20 -n Number of lines to copy.
|
|
21 */
|
|
22
|
|
23 #include "toys.h"
|
|
24
|
|
25 DEFINE_GLOBALS(
|
|
26 long lines;
|
|
27 int file_no;
|
|
28 )
|
|
29
|
|
30 #define TT this.head
|
|
31
|
|
32 static void do_head(int fd, char *name)
|
|
33 {
|
|
34 int i, len, lines=TT.lines, size=sizeof(toybuf);
|
|
35
|
|
36 if (toys.optc > 1) {
|
|
37 // Print an extra newline for all but the first file
|
451
|
38 if (TT.file_no++) xprintf("\n");
|
445
|
39 xprintf("==> %s <==\n", name);
|
451
|
40 xflush();
|
444
|
41 }
|
|
42
|
445
|
43 while (lines) {
|
444
|
44 len = read(fd, toybuf, size);
|
|
45 if (len<0) {
|
|
46 perror_msg("%s",name);
|
|
47 toys.exitval = EXIT_FAILURE;
|
|
48 }
|
|
49 if (len<1) break;
|
|
50
|
445
|
51 for(i=0; i<len;)
|
|
52 if (toybuf[i++] == '\n' && !--lines) break;
|
|
53
|
|
54 xwrite(1, toybuf, i);
|
444
|
55 }
|
|
56 }
|
|
57
|
|
58 void head_main(void)
|
|
59 {
|
|
60 loopfiles(toys.optargs, do_head);
|
|
61 }
|