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