1 /* split.c - split a file into smaller files
2  *
3  * Copyright 2013 Rob Landley <rob@landley.net>
4  *
5  * See http://pubs.opengroup.org/onlinepubs/9699919799/utilities/split.html
6  *
7  * Standard does not cover:
8  * - should splitting an empty file produce an empty outfile? (Went with "no".)
9  * - permissions on output file
10 
11 USE_SPLIT(NEWTOY(split, ">2a#<1=2>9b#<1l#<1[!bl]", TOYFLAG_USR|TOYFLAG_BIN))
12 
13 config SPLIT
14   bool "split"
15   default y
16   help
17     usage: split [-a SUFFIX_LEN] [-b BYTES] [-l LINES] [INPUT [OUTPUT]]
18 
19     Copy INPUT (or stdin) data to a series of OUTPUT (or "x") files with
20     alphabetically increasing suffix (aa, ab, ac... az, ba, bb...).
21 
22     -a	Suffix length (default 2)
23     -b	BYTES/file (10, 10k, 10m, 10g...)
24     -l	LINES/file (default 1000)
25 */
26 
27 #define FOR_split
28 #include "toys.h"
29 
GLOBALS(long l,b,a;char * outfile;)30 GLOBALS(
31   long l, b, a;
32 
33   char *outfile;
34 )
35 
36 static void do_split(int infd, char *in)
37 {
38   unsigned long bytesleft, linesleft, filenum, len, pos;
39   int outfd = -1;
40   struct stat st;
41 
42   // posix doesn't cover permissions on output file, so copy input (or 0777)
43   st.st_mode = 0777;
44   fstat(infd, &st);
45 
46   len = pos = filenum = bytesleft = linesleft = 0;
47   for (;;) {
48     int i, j;
49 
50     // Refill toybuf?
51     if (len == pos) {
52       if (!(len = xread(infd, toybuf, sizeof(toybuf)))) break;
53       pos = 0;
54     }
55 
56     // Start new output file?
57     if ((TT.b && !bytesleft) || (TT.l && !linesleft)) {
58       char *s = TT.outfile + strlen(TT.outfile);
59 
60       j = filenum++;
61       for (i = 0; i<TT.a; i++) {
62         *(--s) = 'a'+(j%26);
63         j /= 26;
64       }
65       if (j) error_exit("bad suffix");
66       bytesleft = TT.b;
67       linesleft = TT.l;
68       if (outfd != -1) close(outfd);
69       outfd = xcreate(TT.outfile, O_RDWR|O_CREAT|O_TRUNC, st.st_mode & 0777);
70     }
71 
72     // Write next chunk of output.
73     if (TT.l) {
74       for (i = pos; i < len; ) {
75         if (toybuf[i++] == '\n' && !--linesleft) break;
76         if (!--bytesleft) break;
77       }
78       j = i - pos;
79     } else {
80       j = len - pos;
81       if (j > bytesleft) j = bytesleft;
82       bytesleft -= j;
83     }
84     xwrite(outfd, toybuf+pos, j);
85     pos += j;
86   }
87 
88   if (CFG_TOYBOX_FREE) {
89     if (outfd != -1) close(outfd);
90     if (infd) close(infd);
91     free(TT.outfile);
92   }
93   xexit();
94 }
95 
split_main(void)96 void split_main(void)
97 {
98   if (!TT.b && !TT.l) TT.l = 1000;
99 
100   // Allocate template for output filenames
101   TT.outfile = xmprintf("%s%*c", (toys.optc == 2) ? toys.optargs[1] : "x",
102     (int)TT.a, ' ');
103 
104   // We only ever use one input, but this handles '-' or no input for us.
105   loopfiles(toys.optargs, do_split);
106 }
107