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 int i, len, lines=TT.n, bytes=TT.c;
38
39 if ((toys.optc > 1 && !(toys.optflags & FLAG_q)) || toys.optflags & FLAG_v) {
40
41 if (TT.file_no) xprintf("\n");
42 xprintf("==> %s <==\n", name);
43 xflush();
44 }
45
46 while ((toys.optflags&FLAG_c) ? bytes : lines) {
47 len = read(fd, toybuf, sizeof(toybuf));
48 if (len<0) perror_msg_raw(name);
49 if (len<1) break;
50
51 if (bytes) {
52 i = bytes >= len ? len : bytes;
53 bytes -= i;
54 } else for(i=0; i<len;) if (toybuf[i++] == '\n' && !--lines) break;
55
56 xwrite(1, toybuf, i);
57 }
58
59 TT.file_no++;
60}
61
62void head_main(void)
63{
64 char *arg = *toys.optargs;
65
66
67 if (arg && *arg == '-' && arg[1]) {
68 TT.n = atolx(arg+1);
69 toys.optc--;
70 } else arg = 0;
71 loopfiles(toys.optargs+!!arg, do_head);
72}
73