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
|
|
9 USE_HEAD(NEWTOY(head, "n#", TOYFLAG_BIN))
|
|
10
|
|
11 config HEAD
|
|
12 bool "head"
|
|
13 default y
|
|
14 help
|
|
15 usage: head [-n number] [file...]
|
|
16 Copy first lines from files to stdout. If no files listed, copy from
|
|
17 stdin. Filename "-" is a synonym for stdin.
|
|
18
|
|
19 -n Number of lines to copy.
|
|
20 */
|
|
21
|
|
22 #include "toys.h"
|
|
23
|
|
24 DEFINE_GLOBALS(
|
|
25 long lines;
|
|
26 int file_no;
|
|
27 )
|
|
28
|
|
29 #define TT this.head
|
|
30
|
|
31 static void do_head(int fd, char *name)
|
|
32 {
|
|
33 int i, len, lines=TT.lines, size=sizeof(toybuf);
|
|
34
|
|
35 if (toys.optc > 1) {
|
|
36 // Print an extra newline for all but the first file
|
|
37 if (TT.file_no++ > 0) printf("\n");
|
|
38 printf("==> %s <==\n", name);
|
|
39 }
|
|
40
|
|
41 for (;lines>0;) {
|
|
42 len = read(fd, toybuf, size);
|
|
43 if (len<0) {
|
|
44 perror_msg("%s",name);
|
|
45 toys.exitval = EXIT_FAILURE;
|
|
46 }
|
|
47 if (len<1) break;
|
|
48
|
|
49 for(i=0; i<len; i++) {
|
|
50 if (toybuf[i] == '\n' && --lines < 1) break;
|
|
51 }
|
|
52 xwrite(1, toybuf, i+1);
|
|
53 }
|
|
54 }
|
|
55
|
|
56 void head_main(void)
|
|
57 {
|
|
58 if (!toys.optflags) TT.lines = 10;
|
|
59 if (TT.lines < 0) perror_exit("Invalid number of lines.");
|
|
60 TT.file_no = 0;
|
|
61 loopfiles(toys.optargs, do_head);
|
|
62 }
|