split.c revision 98253
1250757Sjkim/*
2250757Sjkim * Copyright (c) 1987, 1993, 1994
3250757Sjkim *	The Regents of the University of California.  All rights reserved.
4250757Sjkim *
5250757Sjkim * Redistribution and use in source and binary forms, with or without
6250757Sjkim * modification, are permitted provided that the following conditions
7250757Sjkim * are met:
8250757Sjkim * 1. Redistributions of source code must retain the above copyright
9250757Sjkim *    notice, this list of conditions and the following disclaimer.
10250757Sjkim * 2. Redistributions in binary form must reproduce the above copyright
11250757Sjkim *    notice, this list of conditions and the following disclaimer in the
12250757Sjkim *    documentation and/or other materials provided with the distribution.
13250757Sjkim * 3. All advertising materials mentioning features or use of this software
14250757Sjkim *    must display the following acknowledgement:
15250757Sjkim *	This product includes software developed by the University of
16250757Sjkim *	California, Berkeley and its contributors.
17250757Sjkim * 4. Neither the name of the University nor the names of its contributors
18250757Sjkim *    may be used to endorse or promote products derived from this software
19250757Sjkim *    without specific prior written permission.
20250757Sjkim *
21250757Sjkim * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22250757Sjkim * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23250757Sjkim * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24250757Sjkim * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25250757Sjkim * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26250757Sjkim * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27250757Sjkim * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28250757Sjkim * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29250757Sjkim * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30250757Sjkim * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31250757Sjkim * SUCH DAMAGE.
32250757Sjkim */
33250757Sjkim
34250757Sjkim#include <sys/cdefs.h>
35250757Sjkim__FBSDID("$FreeBSD: head/usr.bin/split/split.c 98253 2002-06-15 11:03:28Z jmallett $");
36250757Sjkim
37250757Sjkim#ifndef lint
38250757Sjkimstatic const char copyright[] =
39250757Sjkim"@(#) Copyright (c) 1987, 1993, 1994\n\
40250757Sjkim	The Regents of the University of California.  All rights reserved.\n";
41250757Sjkim#endif
42250757Sjkim
43250757Sjkim#ifndef lint
44250757Sjkimstatic const char sccsid[] = "@(#)split.c	8.2 (Berkeley) 4/16/94";
45250757Sjkim#endif
46250838Sjkim
47250838Sjkim#include <sys/param.h>
48250757Sjkim
49250757Sjkim#include <ctype.h>
50250757Sjkim#include <err.h>
51250757Sjkim#include <fcntl.h>
52250757Sjkim#include <stdio.h>
53250757Sjkim#include <stdlib.h>
54250757Sjkim#include <string.h>
55250757Sjkim#include <unistd.h>
56250757Sjkim#include <regex.h>
57250757Sjkim#include <sysexits.h>
58250757Sjkim
59250757Sjkim#define DEFLINE	1000			/* Default num lines per file. */
60250757Sjkim
61250757Sjkimint	 bytecnt;			/* Byte count to split on. */
62250757Sjkimlong	 numlines;			/* Line count to split on. */
63250757Sjkimint	 file_open;			/* If a file open. */
64250757Sjkimint	 ifd = -1, ofd = -1;		/* Input/output file descriptors. */
65250757Sjkimchar	 bfr[MAXBSIZE];			/* I/O buffer. */
66250757Sjkimchar	 fname[MAXPATHLEN];		/* File name prefix. */
67250757Sjkimregex_t	 rgx;
68250757Sjkimint	 pflag;
69250757Sjkimlong	 sufflen = 2;			/* File name suffix length. */
70250757Sjkim
71250757Sjkimvoid newfile(void);
72250757Sjkimvoid split1(void);
73250757Sjkimvoid split2(void);
74250757Sjkimstatic void usage(void);
75250757Sjkim
76250757Sjkimint
77250757Sjkimmain(int argc, char **argv)
78250757Sjkim{
79250757Sjkim	int ch;
80250757Sjkim	char *ep, *p;
81250757Sjkim
82250757Sjkim	while ((ch = getopt(argc, argv, "-0123456789a:b:l:p:")) != -1)
83250757Sjkim		switch (ch) {
84250757Sjkim		case '0': case '1': case '2': case '3': case '4':
85250757Sjkim		case '5': case '6': case '7': case '8': case '9':
86250757Sjkim			/*
87250757Sjkim			 * Undocumented kludge: split was originally designed
88250757Sjkim			 * to take a number after a dash.
89250757Sjkim			 */
90250757Sjkim			if (numlines == 0) {
91250757Sjkim				p = argv[optind - 1];
92250757Sjkim				if (p[0] == '-' && p[1] == ch && !p[2])
93250757Sjkim					numlines = strtol(++p, &ep, 10);
94250757Sjkim				else
95250757Sjkim					numlines =
96250757Sjkim					    strtol(argv[optind] + 1, &ep, 10);
97250757Sjkim				if (numlines <= 0 || *ep)
98250757Sjkim					errx(EX_USAGE,
99250757Sjkim					    "%s: illegal line count", optarg);
100250757Sjkim			}
101250757Sjkim			break;
102250757Sjkim		case '-':		/* Undocumented: historic stdin flag. */
103250757Sjkim			if (ifd != -1)
104250757Sjkim				usage();
105250757Sjkim			ifd = 0;
106250757Sjkim			break;
107250757Sjkim		case 'a':		/* Suffix length */
108250757Sjkim			if ((sufflen = strtol(optarg, &ep, 10)) <= 0 || *ep)
109250757Sjkim				errx(EX_USAGE,
110250757Sjkim				    "%s: illegal suffix length", optarg);
111250757Sjkim			break;
112250757Sjkim		case 'b':		/* Byte count. */
113250757Sjkim			if ((bytecnt = strtoq(optarg, &ep, 10)) <= 0 ||
114250757Sjkim			    (*ep != '\0' && *ep != 'k' && *ep != 'm'))
115250757Sjkim				errx(EX_USAGE,
116250757Sjkim				    "%s: illegal byte count", optarg);
117250757Sjkim			if (*ep == 'k')
118250757Sjkim				bytecnt *= 1024;
119250757Sjkim			else if (*ep == 'm')
120250757Sjkim				bytecnt *= 1048576;
121250757Sjkim			break;
122250757Sjkim		case 'p' :      /* pattern matching. */
123250757Sjkim			if (regcomp(&rgx, optarg, REG_EXTENDED|REG_NOSUB) != 0)
124250757Sjkim				errx(EX_USAGE, "%s: illegal regexp", optarg);
125250757Sjkim			pflag = 1;
126250757Sjkim			break;
127250757Sjkim		case 'l':		/* Line count. */
128250757Sjkim			if (numlines != 0)
129250757Sjkim				usage();
130250757Sjkim			if ((numlines = strtol(optarg, &ep, 10)) <= 0 || *ep)
131250757Sjkim				errx(EX_USAGE,
132250757Sjkim				    "%s: illegal line count", optarg);
133250757Sjkim			break;
134250757Sjkim		default:
135250757Sjkim			usage();
136250757Sjkim		}
137250757Sjkim	argv += optind;
138250757Sjkim	argc -= optind;
139250757Sjkim
140250757Sjkim	if (*argv != NULL)
141250757Sjkim		if (ifd == -1) {		/* Input file. */
142250757Sjkim			if (strcmp(*argv, "-") == 0)
143250757Sjkim				ifd = STDIN_FILENO;
144250757Sjkim			else if ((ifd = open(*argv, O_RDONLY, 0)) < 0)
145250757Sjkim				err(EX_NOINPUT, "%s", *argv);
146250757Sjkim			++argv;
147250757Sjkim		}
148250757Sjkim	if (*argv != NULL)			/* File name prefix. */
149250757Sjkim		if (strlcpy(fname, *argv++, sizeof(fname)) >= sizeof(fname))
150250757Sjkim			errx(EX_USAGE, "file name prefix is too long");
151250757Sjkim	if (*argv != NULL)
152250757Sjkim		usage();
153250757Sjkim
154250757Sjkim	if (strlen(fname) + (unsigned long)sufflen >= sizeof(fname))
155250757Sjkim		errx(EX_USAGE, "suffix is too long");
156250757Sjkim	if (pflag && (numlines != 0 || bytecnt != 0))
157250757Sjkim		usage();
158250757Sjkim
159250757Sjkim	if (numlines == 0)
160250757Sjkim		numlines = DEFLINE;
161250757Sjkim	else if (bytecnt != 0)
162250757Sjkim		usage();
163250757Sjkim
164250757Sjkim	if (ifd == -1)				/* Stdin by default. */
165250757Sjkim		ifd = 0;
166250757Sjkim
167250757Sjkim	if (bytecnt) {
168250757Sjkim		split1();
169250757Sjkim		exit (0);
170250757Sjkim	}
171250757Sjkim	split2();
172250757Sjkim	if (pflag)
173250757Sjkim		regfree(&rgx);
174250757Sjkim	exit(0);
175250757Sjkim}
176250757Sjkim
177250757Sjkim/*
178250757Sjkim * split1 --
179250757Sjkim *	Split the input by bytes.
180250757Sjkim */
181250757Sjkimvoid
182250757Sjkimsplit1(void)
183250757Sjkim{
184250757Sjkim	size_t bcnt;
185250757Sjkim	char *C;
186250757Sjkim	int dist, len;
187250757Sjkim
188250757Sjkim	for (bcnt = 0;;)
189250757Sjkim		switch ((len = read(ifd, bfr, MAXBSIZE))) {
190250757Sjkim		case 0:
191250757Sjkim			exit(0);
192250757Sjkim		case -1:
193250757Sjkim			err(EX_IOERR, "read");
194250757Sjkim			/* NOTREACHED */
195250757Sjkim		default:
196250757Sjkim			if (!file_open)
197250757Sjkim				newfile();
198250757Sjkim			if (bcnt + len >= (u_int)bytecnt) {
199250757Sjkim				dist = bytecnt - bcnt;
200250757Sjkim				if (write(ofd, bfr, dist) != dist)
201250757Sjkim					err(EX_IOERR, "write");
202250757Sjkim				len -= dist;
203250757Sjkim				for (C = bfr + dist; len >= bytecnt;
204250757Sjkim				    len -= bytecnt, C += bytecnt) {
205250757Sjkim					newfile();
206250757Sjkim					if (write(ofd,
207250757Sjkim					    C, bytecnt) != bytecnt)
208250757Sjkim						err(EX_IOERR, "write");
209250757Sjkim				}
210250757Sjkim				if (len != 0) {
211250757Sjkim					newfile();
212250757Sjkim					if (write(ofd, C, len) != len)
213250757Sjkim						err(EX_IOERR, "write");
214250757Sjkim				} else
215250757Sjkim					file_open = 0;
216250757Sjkim				bcnt = len;
217250757Sjkim			} else {
218250757Sjkim				bcnt += len;
219250757Sjkim				if (write(ofd, bfr, len) != len)
220250757Sjkim					err(EX_IOERR, "write");
221			}
222		}
223}
224
225/*
226 * split2 --
227 *	Split the input by lines.
228 */
229void
230split2(void)
231{
232	long lcnt = 0;
233	FILE *infp;
234
235	/* Stick a stream on top of input file descriptor */
236	if ((infp = fdopen(ifd, "r")) == NULL)
237		err(EX_NOINPUT, "fdopen");
238
239	/* Process input one line at a time */
240	while (fgets(bfr, sizeof(bfr), infp) != NULL) {
241		const int len = strlen(bfr);
242
243		/* If line is too long to deal with, just write it out */
244		if (bfr[len - 1] != '\n')
245			goto writeit;
246
247		/* Check if we need to start a new file */
248		if (pflag) {
249			regmatch_t pmatch;
250
251			pmatch.rm_so = 0;
252			pmatch.rm_eo = len - 1;
253			if (regexec(&rgx, bfr, 0, &pmatch, REG_STARTEND) == 0)
254				newfile();
255		} else if (lcnt++ == numlines) {
256			newfile();
257			lcnt = 1;
258		}
259
260writeit:
261		/* Open output file if needed */
262		if (!file_open)
263			newfile();
264
265		/* Write out line */
266		if (write(ofd, bfr, len) != len)
267			err(EX_IOERR, "write");
268	}
269
270	/* EOF or error? */
271	if (ferror(infp))
272		err(EX_IOERR, "read");
273	else
274		exit(0);
275}
276
277/*
278 * newfile --
279 *	Open a new output file.
280 */
281void
282newfile(void)
283{
284	long i, maxfiles, tfnum;
285	static long fnum;
286	static int defname;
287	static char *fpnt;
288
289	if (ofd == -1) {
290		if (fname[0] == '\0') {
291			fname[0] = 'x';
292			fpnt = fname + 1;
293			defname = 1;
294		} else {
295			fpnt = fname + strlen(fname);
296			defname = 0;
297		}
298		ofd = fileno(stdout);
299	}
300
301	/* maxfiles = 26^sufflen, but don't use libm. */
302	for (maxfiles = 1, i = 0; i < sufflen; i++)
303		if ((maxfiles *= 26) <= 0)
304			errx(EX_USAGE, "suffix is too long (max %ld)", i);
305
306	/*
307	 * Hack to increase max files; original code wandered through
308	 * magic characters.
309	 */
310	if (fnum == maxfiles) {
311		if (!defname || fname[0] == 'z')
312			errx(EX_DATAERR, "too many files");
313		++fname[0];
314		fnum = 0;
315	}
316
317	/* Generate suffix of sufflen letters */
318	tfnum = fnum;
319	i = sufflen - 1;
320	do {
321		fpnt[i] = tfnum % 26 + 'a';
322		tfnum /= 26;
323	} while (i-- > 0);
324	fpnt[sufflen] = '\0';
325
326	++fnum;
327	if (!freopen(fname, "w", stdout))
328		err(EX_IOERR, "%s", fname);
329	file_open = 1;
330}
331
332static void
333usage(void)
334{
335	(void)fprintf(stderr,
336"usage: split [-a sufflen] [-b byte_count] [-l line_count] [-p pattern]\n");
337	(void)fprintf(stderr,
338"             [file [prefix]]\n");
339	exit(EX_USAGE);
340}
341