1 /* split.c - split a file into smaller files
3 * Copyright 2013 Rob Landley <rob@landley.net>
5 * See http://pubs.opengroup.org/onlinepubs/9699919799/utilities/split.html
7 * Standard does not cover:
8 * - should splitting an empty file produce an empty outfile? (Went with "no".)
9 * - permissions on output file
11 USE_SPLIT(NEWTOY(split, ">2a#<1=2>9b#<1l#<1[!bl]", TOYFLAG_USR|TOYFLAG_BIN))
17 usage: split [-a SUFFIX_LEN] [-b BYTES] [-l LINES] [INPUT [OUTPUT]]
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...).
22 -a Suffix length (default 2)
23 -b BYTES/file (10, 10k, 10m, 10g...)
24 -l LINES/file (default 1000)
38 static void do_split(int infd, char *in)
40 unsigned long bytesleft, linesleft, filenum, len, pos;
44 // posix doesn't cover permissions on output file, so copy input (or 0777)
48 len = pos = filenum = bytesleft = linesleft = 0;
54 if (!(len = xread(infd, toybuf, sizeof(toybuf)))) break;
58 // Start new output file?
59 if ((TT.bytes && !bytesleft) || (TT.lines && !linesleft)) {
60 char *s = TT.outfile + strlen(TT.outfile);
63 for (i = 0; i<TT.suflen; i++) {
67 if (j) error_exit("bad suffix");
70 if (outfd != -1) close(outfd);
71 outfd = xcreate(TT.outfile, O_RDWR|O_CREAT|O_TRUNC, st.st_mode & 0777);
74 // Write next chunk of output.
76 for (i = pos; i < len; ) {
77 if (toybuf[i++] == '\n' && !--linesleft) break;
78 if (!--bytesleft) break;
83 if (j > bytesleft) j = bytesleft;
86 xwrite(outfd, toybuf+pos, j);
90 if (CFG_TOYBOX_FREE) {
91 if (outfd != -1) close(outfd);
92 if (infd) close(infd);
100 if (!TT.bytes && !TT.lines) TT.lines = 1000;
102 // Allocate template for output filenames
103 TT.outfile = xmprintf("%s%*c", (toys.optc == 2) ? toys.optargs[1] : "x",
104 (int)TT.suflen, ' ');
106 // We only ever use one input, but this handles '-' or no input for us.
107 loopfiles(toys.optargs, do_split);