split.c revision 1590
1/*
2 * Copyright (c) 1987, 1993, 1994
3 *	The Regents of the University of California.  All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in the
12 *    documentation and/or other materials provided with the distribution.
13 * 3. All advertising materials mentioning features or use of this software
14 *    must display the following acknowledgement:
15 *	This product includes software developed by the University of
16 *	California, Berkeley and its contributors.
17 * 4. Neither the name of the University nor the names of its contributors
18 *    may be used to endorse or promote products derived from this software
19 *    without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
32 */
33
34#ifndef lint
35static char copyright[] =
36"@(#) Copyright (c) 1987, 1993, 1994\n\
37	The Regents of the University of California.  All rights reserved.\n";
38#endif /* not lint */
39
40#ifndef lint
41static char sccsid[] = "@(#)split.c	8.2 (Berkeley) 4/16/94";
42#endif /* not lint */
43
44#include <sys/param.h>
45
46#include <ctype.h>
47#include <err.h>
48#include <fcntl.h>
49#include <stdio.h>
50#include <stdlib.h>
51#include <string.h>
52#include <unistd.h>
53
54#define DEFLINE	1000			/* Default num lines per file. */
55
56long	 bytecnt;			/* Byte count to split on. */
57long	 numlines;			/* Line count to split on. */
58int	 file_open;			/* If a file open. */
59int	 ifd = -1, ofd = -1;		/* Input/output file descriptors. */
60char	 bfr[MAXBSIZE];			/* I/O buffer. */
61char	 fname[MAXPATHLEN];		/* File name prefix. */
62
63void newfile __P((void));
64void split1 __P((void));
65void split2 __P((void));
66void usage __P((void));
67
68int
69main(argc, argv)
70	int argc;
71	char *argv[];
72{
73	int ch;
74	char *ep, *p;
75
76	while ((ch = getopt(argc, argv, "-0123456789b:l:")) != EOF)
77		switch (ch) {
78		case '0': case '1': case '2': case '3': case '4':
79		case '5': case '6': case '7': case '8': case '9':
80			/*
81			 * Undocumented kludge: split was originally designed
82			 * to take a number after a dash.
83			 */
84			if (numlines == 0) {
85				p = argv[optind - 1];
86				if (p[0] == '-' && p[1] == ch && !p[2])
87					numlines = strtol(++p, &ep, 10);
88				else
89					numlines =
90					    strtol(argv[optind] + 1, &ep, 10);
91				if (numlines <= 0 || *ep)
92					errx(1,
93					    "%s: illegal line count.", optarg);
94			}
95			break;
96		case '-':		/* Undocumented: historic stdin flag. */
97			if (ifd != -1)
98				usage();
99			ifd = 0;
100			break;
101		case 'b':		/* Byte count. */
102			if ((bytecnt = strtol(optarg, &ep, 10)) <= 0 ||
103			    *ep != '\0' && *ep != 'k' && *ep != 'm')
104				errx(1, "%s: illegal byte count.", optarg);
105			if (*ep == 'k')
106				bytecnt *= 1024;
107			else if (*ep == 'm')
108				bytecnt *= 1048576;
109			break;
110		case 'l':		/* Line count. */
111			if (numlines != 0)
112				usage();
113			if ((numlines = strtol(optarg, &ep, 10)) <= 0 || *p)
114				errx(1, "%s: illegal line count.", optarg);
115			break;
116		default:
117			usage();
118		}
119	argv += optind;
120	argc -= optind;
121
122	if (*argv != NULL)
123		if (ifd == -1) {		/* Input file. */
124			if ((ifd = open(*argv, O_RDONLY, 0)) < 0)
125				err(1, "%s", *argv);
126			++argv;
127		}
128	if (*argv != NULL)			/* File name prefix. */
129		(void)strcpy(fname, *argv++);
130	if (*argv != NULL)
131		usage();
132
133	if (numlines == 0)
134		numlines = DEFLINE;
135	else if (bytecnt)
136		usage();
137
138	if (ifd == -1)				/* Stdin by default. */
139		ifd = 0;
140
141	if (bytecnt) {
142		split1();
143		exit (0);
144	}
145	split2();
146	exit(0);
147}
148
149/*
150 * split1 --
151 *	Split the input by bytes.
152 */
153void
154split1()
155{
156	long bcnt;
157	int dist, len;
158	char *C;
159
160	for (bcnt = 0;;)
161		switch (len = read(ifd, bfr, MAXBSIZE)) {
162		case 0:
163			exit(0);
164		case -1:
165			err(1, "read");
166			/* NOTREACHED */
167		default:
168			if (!file_open) {
169				newfile();
170				file_open = 1;
171			}
172			if (bcnt + len >= bytecnt) {
173				dist = bytecnt - bcnt;
174				if (write(ofd, bfr, dist) != dist)
175					err(1, "write");
176				len -= dist;
177				for (C = bfr + dist; len >= bytecnt;
178				    len -= bytecnt, C += bytecnt) {
179					newfile();
180					if (write(ofd,
181					    C, (int)bytecnt) != bytecnt)
182						err(1, "write");
183				}
184				if (len) {
185					newfile();
186					if (write(ofd, C, len) != len)
187						err(1, "write");
188				} else
189					file_open = 0;
190				bcnt = len;
191			} else {
192				bcnt += len;
193				if (write(ofd, bfr, len) != len)
194					err(1, "write");
195			}
196		}
197}
198
199/*
200 * split2 --
201 *	Split the input by lines.
202 */
203void
204split2()
205{
206	long lcnt;
207	int len, bcnt;
208	char *Ce, *Cs;
209
210	for (lcnt = 0;;)
211		switch (len = read(ifd, bfr, MAXBSIZE)) {
212		case 0:
213			exit(0);
214		case -1:
215			err(1, "read");
216			/* NOTREACHED */
217		default:
218			if (!file_open) {
219				newfile();
220				file_open = 1;
221			}
222			for (Cs = Ce = bfr; len--; Ce++)
223				if (*Ce == '\n' && ++lcnt == numlines) {
224					bcnt = Ce - Cs + 1;
225					if (write(ofd, Cs, bcnt) != bcnt)
226						err(1, "write");
227					lcnt = 0;
228					Cs = Ce + 1;
229					if (len)
230						newfile();
231					else
232						file_open = 0;
233				}
234			if (Cs < Ce) {
235				bcnt = Ce - Cs;
236				if (write(ofd, Cs, bcnt) != bcnt)
237					err(1, "write");
238			}
239		}
240}
241
242/*
243 * newfile --
244 *	Open a new output file.
245 */
246void
247newfile()
248{
249	static long fnum;
250	static int defname;
251	static char *fpnt;
252
253	if (ofd == -1) {
254		if (fname[0] == '\0') {
255			fname[0] = 'x';
256			fpnt = fname + 1;
257			defname = 1;
258		} else {
259			fpnt = fname + strlen(fname);
260			defname = 0;
261		}
262		ofd = fileno(stdout);
263	}
264	/*
265	 * Hack to increase max files; original code wandered through
266	 * magic characters.  Maximum files is 3 * 26 * 26 == 2028
267	 */
268#define MAXFILES	676
269	if (fnum == MAXFILES) {
270		if (!defname || fname[0] == 'z')
271			errx(1, "too many files.");
272		++fname[0];
273		fnum = 0;
274	}
275	fpnt[0] = fnum / 26 + 'a';
276	fpnt[1] = fnum % 26 + 'a';
277	++fnum;
278	if (!freopen(fname, "w", stdout))
279		err(1, "%s", fname);
280}
281
282void
283usage()
284{
285	(void)fprintf(stderr,
286"usage: split [-b byte_count] [-l line_count] [file [prefix]]\n");
287	exit(1);
288}
289