xref: /freebsd/usr.bin/split/split.c (revision 91180daf65df4fdd1bb8b9f3b27f22937f1622a5)
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 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
36 
37 #ifndef lint
38 static const char copyright[] =
39 "@(#) Copyright (c) 1987, 1993, 1994\n\
40 	The Regents of the University of California.  All rights reserved.\n";
41 #endif
42 
43 #ifndef lint
44 static const char sccsid[] = "@(#)split.c	8.2 (Berkeley) 4/16/94";
45 #endif
46 
47 #include <sys/param.h>
48 #include <sys/types.h>
49 
50 #include <ctype.h>
51 #include <err.h>
52 #include <fcntl.h>
53 #include <stdio.h>
54 #include <stdlib.h>
55 #include <string.h>
56 #include <unistd.h>
57 #include <regex.h>
58 #include <sysexits.h>
59 
60 #define DEFLINE	1000			/* Default num lines per file. */
61 
62 int	 bytecnt;			/* Byte count to split on. */
63 long	 numlines;			/* Line count to split on. */
64 int	 file_open;			/* If a file open. */
65 int	 ifd = -1, ofd = -1;		/* Input/output file descriptors. */
66 char	 bfr[MAXBSIZE];			/* I/O buffer. */
67 char	 fname[MAXPATHLEN];		/* File name prefix. */
68 regex_t	 rgx;
69 int	 pflag;
70 long	 sufflen = 2;			/* File name suffix length. */
71 
72 void newfile(void);
73 void split1(void);
74 void split2(void);
75 static void usage(void);
76 
77 int
78 main(argc, argv)
79 	int argc;
80 	char *argv[];
81 {
82 	int ch;
83 	char *ep, *p;
84 
85 	while ((ch = getopt(argc, argv, "-0123456789a:b:l:p:")) != -1)
86 		switch (ch) {
87 		case '0': case '1': case '2': case '3': case '4':
88 		case '5': case '6': case '7': case '8': case '9':
89 			/*
90 			 * Undocumented kludge: split was originally designed
91 			 * to take a number after a dash.
92 			 */
93 			if (numlines == 0) {
94 				p = argv[optind - 1];
95 				if (p[0] == '-' && p[1] == ch && !p[2])
96 					numlines = strtol(++p, &ep, 10);
97 				else
98 					numlines =
99 					    strtol(argv[optind] + 1, &ep, 10);
100 				if (numlines <= 0 || *ep)
101 					errx(EX_USAGE,
102 					    "%s: illegal line count", optarg);
103 			}
104 			break;
105 		case '-':		/* Undocumented: historic stdin flag. */
106 			if (ifd != -1)
107 				usage();
108 			ifd = 0;
109 			break;
110 		case 'a':		/* Suffix length */
111 			if ((sufflen = strtol(optarg, &ep, 10)) <= 0 || *ep)
112 				errx(EX_USAGE,
113 				    "%s: illegal suffix length", optarg);
114 			break;
115 		case 'b':		/* Byte count. */
116 			if ((bytecnt = strtoq(optarg, &ep, 10)) <= 0 ||
117 			    (*ep != '\0' && *ep != 'k' && *ep != 'm'))
118 				errx(EX_USAGE,
119 				    "%s: illegal byte count", optarg);
120 			if (*ep == 'k')
121 				bytecnt *= 1024;
122 			else if (*ep == 'm')
123 				bytecnt *= 1048576;
124 			break;
125 		case 'p' :      /* pattern matching. */
126 			if (regcomp(&rgx, optarg, REG_EXTENDED|REG_NOSUB) != 0)
127 				errx(EX_USAGE, "%s: illegal regexp", optarg);
128 			pflag = 1;
129 			break;
130 		case 'l':		/* Line count. */
131 			if (numlines != 0)
132 				usage();
133 			if ((numlines = strtol(optarg, &ep, 10)) <= 0 || *ep)
134 				errx(EX_USAGE,
135 				    "%s: illegal line count", optarg);
136 			break;
137 		default:
138 			usage();
139 		}
140 	argv += optind;
141 	argc -= optind;
142 
143 	if (*argv != NULL)
144 		if (ifd == -1) {		/* Input file. */
145 			if (strcmp(*argv, "-") == 0)
146 				ifd = STDIN_FILENO;
147 			else if ((ifd = open(*argv, O_RDONLY, 0)) < 0)
148 				err(EX_NOINPUT, "%s", *argv);
149 			++argv;
150 		}
151 	if (*argv != NULL)			/* File name prefix. */
152 		if (strlcpy(fname, *argv++, sizeof(fname)) >= sizeof(fname))
153 			errx(EX_USAGE, "file name prefix is too long");
154 	if (*argv != NULL)
155 		usage();
156 
157 	if (strlen(fname) + (unsigned long)sufflen >= sizeof(fname))
158 		errx(EX_USAGE, "suffix is too long");
159 	if (pflag && (numlines != 0 || bytecnt != 0))
160 		usage();
161 
162 	if (numlines == 0)
163 		numlines = DEFLINE;
164 	else if (bytecnt != 0)
165 		usage();
166 
167 	if (ifd == -1)				/* Stdin by default. */
168 		ifd = 0;
169 
170 	if (bytecnt) {
171 		split1();
172 		exit (0);
173 	}
174 	split2();
175 	if (pflag)
176 		regfree(&rgx);
177 	exit(0);
178 }
179 
180 /*
181  * split1 --
182  *	Split the input by bytes.
183  */
184 void
185 split1()
186 {
187 	size_t bcnt;
188 	char *C;
189 	int dist, len;
190 
191 	for (bcnt = 0;;)
192 		switch ((len = read(ifd, bfr, MAXBSIZE))) {
193 		case 0:
194 			exit(0);
195 		case -1:
196 			err(EX_IOERR, "read");
197 			/* NOTREACHED */
198 		default:
199 			if (!file_open)
200 				newfile();
201 			if (bcnt + len >= (u_int)bytecnt) {
202 				dist = bytecnt - bcnt;
203 				if (write(ofd, bfr, dist) != dist)
204 					err(EX_IOERR, "write");
205 				len -= dist;
206 				for (C = bfr + dist; len >= bytecnt;
207 				    len -= bytecnt, C += bytecnt) {
208 					newfile();
209 					if (write(ofd,
210 					    C, bytecnt) != bytecnt)
211 						err(EX_IOERR, "write");
212 				}
213 				if (len != 0) {
214 					newfile();
215 					if (write(ofd, C, len) != len)
216 						err(EX_IOERR, "write");
217 				} else
218 					file_open = 0;
219 				bcnt = len;
220 			} else {
221 				bcnt += len;
222 				if (write(ofd, bfr, len) != len)
223 					err(EX_IOERR, "write");
224 			}
225 		}
226 }
227 
228 /*
229  * split2 --
230  *	Split the input by lines.
231  */
232 void
233 split2()
234 {
235 	long lcnt = 0;
236 	FILE *infp;
237 
238 	/* Stick a stream on top of input file descriptor */
239 	if ((infp = fdopen(ifd, "r")) == NULL)
240 		err(EX_NOINPUT, "fdopen");
241 
242 	/* Process input one line at a time */
243 	while (fgets(bfr, sizeof(bfr), infp) != NULL) {
244 		const int len = strlen(bfr);
245 
246 		/* If line is too long to deal with, just write it out */
247 		if (bfr[len - 1] != '\n')
248 			goto writeit;
249 
250 		/* Check if we need to start a new file */
251 		if (pflag) {
252 			regmatch_t pmatch;
253 
254 			pmatch.rm_so = 0;
255 			pmatch.rm_eo = len - 1;
256 			if (regexec(&rgx, bfr, 0, &pmatch, REG_STARTEND) == 0)
257 				newfile();
258 		} else if (lcnt++ == numlines) {
259 			newfile();
260 			lcnt = 1;
261 		}
262 
263 writeit:
264 		/* Open output file if needed */
265 		if (!file_open)
266 			newfile();
267 
268 		/* Write out line */
269 		if (write(ofd, bfr, len) != len)
270 			err(EX_IOERR, "write");
271 	}
272 
273 	/* EOF or error? */
274 	if (ferror(infp))
275 		err(EX_IOERR, "read");
276 	else
277 		exit(0);
278 }
279 
280 /*
281  * newfile --
282  *	Open a new output file.
283  */
284 void
285 newfile()
286 {
287 	long i, maxfiles, tfnum;
288 	static long fnum;
289 	static int defname;
290 	static char *fpnt;
291 
292 	if (ofd == -1) {
293 		if (fname[0] == '\0') {
294 			fname[0] = 'x';
295 			fpnt = fname + 1;
296 			defname = 1;
297 		} else {
298 			fpnt = fname + strlen(fname);
299 			defname = 0;
300 		}
301 		ofd = fileno(stdout);
302 	}
303 
304 	/* maxfiles = 26^sufflen, but don't use libm. */
305 	for (maxfiles = 1, i = 0; i < sufflen; i++)
306 		if ((maxfiles *= 26) <= 0)
307 			errx(EX_USAGE, "suffix is too long (max %ld)", i);
308 
309 	/*
310 	 * Hack to increase max files; original code wandered through
311 	 * magic characters.
312 	 */
313 	if (fnum == maxfiles) {
314 		if (!defname || fname[0] == 'z')
315 			errx(EX_DATAERR, "too many files");
316 		++fname[0];
317 		fnum = 0;
318 	}
319 
320 	/* Generate suffix of sufflen letters */
321 	tfnum = fnum;
322 	i = sufflen - 1;
323 	do {
324 		fpnt[i] = tfnum % 26 + 'a';
325 		tfnum /= 26;
326 	} while (i-- > 0);
327 	fpnt[sufflen] = '\0';
328 
329 	++fnum;
330 	if (!freopen(fname, "w", stdout))
331 		err(EX_IOERR, "%s", fname);
332 	file_open = 1;
333 }
334 
335 static void
336 usage()
337 {
338 	(void)fprintf(stderr,
339 "usage: split [-a sufflen] [-b byte_count] [-l line_count] [-p pattern]\n");
340 	(void)fprintf(stderr,
341 "             [file [prefix]]\n");
342 	exit(EX_USAGE);
343 }
344