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
27#define FOR_split
28#include "toys.h"
29
30GLOBALS(
31 long lines;
32 long bytes;
33 long suflen;
34
35 char *outfile;
36)
37
38static void do_split(int infd, char *in)
39{
40 unsigned long bytesleft, linesleft, filenum, len, pos;
41 int outfd = -1;
42 struct stat st;
43
44
45 st.st_mode = 0777;
46 fstat(infd, &st);
47
48 len = pos = filenum = bytesleft = linesleft = 0;
49 for (;;) {
50 int i, j;
51
52
53 if (len == pos) {
54 if (!(len = xread(infd, toybuf, sizeof(toybuf)))) break;
55 pos = 0;
56 }
57
58
59 if ((TT.bytes && !bytesleft) || (TT.lines && !linesleft)) {
60 char *s = TT.outfile + strlen(TT.outfile);
61
62 j = filenum++;
63 for (i = 0; i<TT.suflen; i++) {
64 *(--s) = 'a'+(j%26);
65 j /= 26;
66 }
67 if (j) error_exit("bad suffix");
68 bytesleft = TT.bytes;
69 linesleft = TT.lines;
70 if (outfd != -1) close(outfd);
71 outfd = xcreate(TT.outfile, O_RDWR|O_CREAT|O_TRUNC, st.st_mode & 0777);
72 }
73
74
75 if (TT.lines) {
76 for (i = pos; i < len; ) {
77 if (toybuf[i++] == '\n' && !--linesleft) break;
78 if (!--bytesleft) break;
79 }
80 j = i - pos;
81 } else {
82 j = len - pos;
83 if (j > bytesleft) j = bytesleft;
84 bytesleft -= j;
85 }
86 xwrite(outfd, toybuf+pos, j);
87 pos += j;
88 }
89
90 if (CFG_TOYBOX_FREE) {
91 if (outfd != -1) close(outfd);
92 if (infd) close(infd);
93 free(TT.outfile);
94 }
95 xexit();
96}
97
98void split_main(void)
99{
100 if (!TT.bytes && !TT.lines) TT.lines = 1000;
101
102
103 TT.outfile = xmprintf("%s%*c", (toys.optc == 2) ? toys.optargs[1] : "x",
104 (int)TT.suflen, ' ');
105
106
107 loopfiles(toys.optargs, do_split);
108}
109