1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26#define FOR_head
27#include "toys.h"
28
29GLOBALS(
30 long c, n;
31
32 int file_no;
33)
34
35static void do_head(int fd, char *name)
36{
37 long i, len, lines=TT.n, bytes=TT.c;
38
39 if ((toys.optc > 1 && !FLAG(q)) || FLAG(v)) {
40
41 if (TT.file_no) xprintf("\n");
42 xprintf("==> %s <==\n", name);
43 }
44
45 while (FLAG(c) ? bytes : lines) {
46 len = read(fd, toybuf, sizeof(toybuf));
47 if (len<0) perror_msg_raw(name);
48 if (len<1) break;
49
50 if (bytes) {
51 i = bytes >= len ? len : bytes;
52 bytes -= i;
53 } else for(i=0; i<len;) if (toybuf[i++] == '\n' && !--lines) break;
54
55 xwrite(1, toybuf, i);
56 }
57
58 TT.file_no++;
59}
60
61void head_main(void)
62{
63 char *arg = *toys.optargs;
64
65
66 if (arg && *arg == '-' && arg[1]) {
67 TT.n = atolx(arg+1);
68 toys.optc--;
69 } else arg = 0;
70 loopfiles(toys.optargs+!!arg, do_head);
71}
72