xref: /dragonfly/usr.bin/split/split.c (revision 37de577a)
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. Neither the name of the University nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  * @(#) Copyright (c) 1987, 1993, 1994 The Regents of the University of California.  All rights reserved.
30  * @(#)split.c	8.2 (Berkeley) 4/16/94
31  * $FreeBSD: src/usr.bin/split/split.c,v 1.6.2.2 2002/07/25 12:46:36 tjr Exp $
32  */
33 
34 #include <sys/param.h>
35 
36 #include <ctype.h>
37 #include <err.h>
38 #include <errno.h>
39 #include <fcntl.h>
40 #include <libutil.h>
41 #include <limits.h>
42 #include <stdbool.h>
43 #include <stdio.h>
44 #include <stdlib.h>
45 #include <string.h>
46 #include <unistd.h>
47 #include <regex.h>
48 #include <sysexits.h>
49 
50 #define DEFLINE	1000			/* Default num lines per file. */
51 
52 static int64_t	 bytecnt;		/* Byte count to split on. */
53 static long	 numlines;		/* Line count to split on. */
54 static int	 file_open;		/* If a file open. */
55 static int	 ifd = -1, ofd = -1;	/* Input/output file descriptors. */
56 static char	 *bfr;			/* I/O buffer. */
57 static char	 fname[MAXPATHLEN];	/* File name prefix. */
58 static regex_t	 rgx;
59 static bool	 dflag;
60 static int	 pflag;
61 static long	 sufflen = 2;		/* File name suffix length. */
62 
63 static void newfile(void);
64 static void split1(void);
65 static void split2(void);
66 static void usage(void);
67 
68 int
69 main(int argc, char **argv)
70 {
71 	int ch;
72 	char *ep, *p;
73 	int error;
74 
75 	while ((ch = getopt(argc, argv, "0123456789a:b:dl:p:")) != -1)
76 		switch (ch) {
77 		case '0': case '1': case '2': case '3': case '4':
78 		case '5': case '6': case '7': case '8': case '9':
79 			/*
80 			 * Undocumented kludge: split was originally designed
81 			 * to take a number after a dash.
82 			 */
83 			if (numlines == 0) {
84 				p = argv[optind - 1];
85 				if (p[0] == '-' && p[1] == ch && !p[2])
86 					numlines = strtol(++p, &ep, 10);
87 				else
88 					numlines =
89 					    strtol(argv[optind] + 1, &ep, 10);
90 				if (numlines <= 0 || *ep)
91 					errx(EX_USAGE,
92 					    "%s: illegal line count", optarg);
93 			}
94 			break;
95 		case 'a':		/* Suffix length */
96 			if ((sufflen = strtol(optarg, &ep, 10)) <= 0 || *ep)
97 				errx(EX_USAGE,
98 				    "%s: illegal suffix length", optarg);
99 			break;
100 		case 'b':		/* Byte count. */
101 			error = dehumanize_number(optarg, &bytecnt);
102 			if (error != 0)
103 				errx(EX_USAGE, "%s: illegal byte count",
104 				    optarg);
105 			break;
106 		case 'd':	/* Decimal suffix */
107 			dflag = true;
108 			break;
109 		case 'p' :      /* pattern matching. */
110 			if (regcomp(&rgx, optarg, REG_EXTENDED|REG_NOSUB) != 0)
111 				errx(EX_USAGE, "%s: illegal regexp", optarg);
112 			pflag = 1;
113 			break;
114 		case 'l':		/* Line count. */
115 			if (numlines != 0)
116 				usage();
117 			if ((numlines = strtol(optarg, &ep, 10)) <= 0 || *ep)
118 				errx(EX_USAGE,
119 				    "%s: illegal line count", optarg);
120 			break;
121 		default:
122 			usage();
123 		}
124 	argv += optind;
125 	argc -= optind;
126 
127 	if (*argv != NULL) {
128 		if (strcmp(*argv, "-") == 0)
129 			ifd = STDIN_FILENO;
130 		else if ((ifd = open(*argv, O_RDONLY, 0)) < 0)
131 			err(EX_NOINPUT, "%s", *argv);
132 		++argv;
133 	}
134 
135 	if (*argv != NULL)			/* File name prefix. */
136 		if (strlcpy(fname, *argv++, sizeof(fname)) >= sizeof(fname))
137 			errx(EX_USAGE, "file name prefix is too long");
138 	if (*argv != NULL)
139 		usage();
140 
141 	if (strlen(fname) + (unsigned long)sufflen >= sizeof(fname))
142 		errx(EX_USAGE, "suffix is too long");
143 	if (pflag && (numlines != 0 || bytecnt != 0))
144 		usage();
145 
146 	if (numlines == 0)
147 		numlines = DEFLINE;
148 	else if (bytecnt != 0)
149 		usage();
150 
151 	if (ifd == -1)				/* Stdin by default. */
152 		ifd = 0;
153 
154 	if (bytecnt) {
155 		split1();
156 		exit (0);
157 	}
158 	split2();
159 	if (pflag)
160 		regfree(&rgx);
161 	exit(0);
162 }
163 
164 /*
165  * split1 --
166  *	Split the input by bytes.
167  */
168 static void
169 split1(void)
170 {
171 	off_t bcnt;
172 	char *C;
173 	ssize_t dist, len;
174 
175 	if((bfr = (char *)malloc(bytecnt)) == NULL)
176 		err(EX_OSERR, "malloc");
177 
178 	for (bcnt = 0;;)
179 		switch ((len = read(ifd, bfr, bytecnt))) {
180 		case 0:
181 			free(bfr);
182 			exit(0);
183 		case -1:
184 			free(bfr);
185 			err(EX_IOERR, "read");
186 			/* NOTREACHED */
187 		default:
188 			if (!file_open)
189 				newfile();
190 			if (bcnt + len >= bytecnt) {
191 				dist = bytecnt - bcnt;
192 				if (write(ofd, bfr, dist) != dist)
193 					err(EX_IOERR, "write");
194 				len -= dist;
195 				for (C = bfr + dist; len >= bytecnt;
196 				    len -= bytecnt, C += bytecnt) {
197 					newfile();
198 					if (write(ofd,
199 					    C, (int)bytecnt) != bytecnt) {
200 						free(bfr);
201 						err(EX_IOERR, "write");
202 					}
203 				}
204 				if (len != 0) {
205 					newfile();
206 					if (write(ofd, C, len) != len) {
207 						free(bfr);
208 						err(EX_IOERR, "write");
209 					}
210 				} else
211 					file_open = 0;
212 				bcnt = len;
213 			} else {
214 				bcnt += len;
215 				if (write(ofd, bfr, len) != len) {
216 					free(bfr);
217 					err(EX_IOERR, "write");
218 				}
219 			}
220 		}
221 	free(bfr);
222 }
223 
224 /*
225  * split2 --
226  *	Split the input by lines.
227  */
228 static void
229 split2(void)
230 {
231 	int startofline = 1;
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 	if((bfr = (char *)malloc(MAXBSIZE)) == NULL)
240 		err(EX_OSERR, "malloc");
241 
242 	/* Process input one line at a time */
243 	while (fgets(bfr, MAXBSIZE, infp) != NULL) {
244 		const int len = strlen(bfr);
245 
246 		/* Consider starting a new file only when at beginning of a line */
247 		if (startofline) {
248 			/* Check if we need to start a new file */
249 			if (pflag) {
250 				regmatch_t pmatch;
251 
252 				pmatch.rm_so = 0;
253 				pmatch.rm_eo = len - 1;
254 				if (regexec(&rgx, bfr, 0, &pmatch, REG_STARTEND) == 0)
255 					newfile();
256 			} else if (lcnt++ == numlines) {
257 				newfile();
258 				lcnt = 1;
259 			}
260 		}
261 
262 		if (bfr[len - 1] != '\n')
263 			startofline = 0;
264 		else
265 			startofline = 1;
266 
267 		/* Open output file if needed */
268 		if (!file_open)
269 			newfile();
270 
271 		/* Write out line */
272 		if (write(ofd, bfr, len) != len) {
273 			free(bfr);
274 			err(EX_IOERR, "write");
275 		}
276 	}
277 
278 	free(bfr);
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 static void
292 newfile(void)
293 {
294 	long i, maxfiles, tfnum;
295 	static long fnum;
296 	static char *fpnt;
297 	char beg, end;
298 	int pattlen;
299 
300 	if (ofd == -1) {
301 		if (fname[0] == '\0') {
302 			fname[0] = 'x';
303 			fpnt = fname + 1;
304 		} else {
305 			fpnt = fname + strlen(fname);
306 		}
307 		ofd = fileno(stdout);
308 	}
309 
310 	if (dflag) {
311 		beg = '0';
312 		end = '9';
313 	}
314 	else {
315 		beg = 'a';
316 		end = 'z';
317 	}
318 	pattlen = end - beg + 1;
319 
320 	/* maxfiles = pattlen^sufflen, but don't use libm. */
321 	for (maxfiles = 1, i = 0; i < sufflen; i++)
322 		if (LONG_MAX / pattlen < maxfiles)
323 			errx(EX_USAGE, "suffix is too long (max %ld)", i);
324 		else
325 			maxfiles *= pattlen;
326 
327 	if (fnum == maxfiles)
328 		errx(EX_DATAERR, "too many files");
329 
330 	/* Generate suffix of sufflen letters */
331 	tfnum = fnum;
332 	i = sufflen - 1;
333 	do {
334 		fpnt[i] = tfnum % pattlen + beg;
335 		tfnum /= pattlen;
336 	} while (i-- > 0);
337 	fpnt[sufflen] = '\0';
338 
339 	++fnum;
340 	if (!freopen(fname, "w", stdout))
341 		err(EX_IOERR, "%s", fname);
342 	file_open = 1;
343 }
344 
345 static void
346 usage(void)
347 {
348 	(void)fprintf(stderr,
349 "usage: split [-a sufflen] [-b byte_count] [-l line_count] [-p pattern]\n");
350 	(void)fprintf(stderr,
351 "             [file [prefix]]\n");
352 	exit(EX_USAGE);
353 }
354