xref: /freebsd/usr.bin/split/split.c (revision 9207b4cff7b8d483f4dd3c62266c2b58819eb7f9)
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 
71 void newfile __P((void));
72 void split1 __P((void));
73 void split2 __P((void));
74 static void usage __P((void));
75 
76 int
77 main(argc, argv)
78 	int argc;
79 	char *argv[];
80 {
81 	int ch;
82 	char *ep, *p;
83 
84 	while ((ch = getopt(argc, argv, "-0123456789b:l:p:")) != -1)
85 		switch (ch) {
86 		case '0': case '1': case '2': case '3': case '4':
87 		case '5': case '6': case '7': case '8': case '9':
88 			/*
89 			 * Undocumented kludge: split was originally designed
90 			 * to take a number after a dash.
91 			 */
92 			if (numlines == 0) {
93 				p = argv[optind - 1];
94 				if (p[0] == '-' && p[1] == ch && !p[2])
95 					numlines = strtol(++p, &ep, 10);
96 				else
97 					numlines =
98 					    strtol(argv[optind] + 1, &ep, 10);
99 				if (numlines <= 0 || *ep)
100 					errx(EX_USAGE,
101 					    "%s: illegal line count", optarg);
102 			}
103 			break;
104 		case '-':		/* Undocumented: historic stdin flag. */
105 			if (ifd != -1)
106 				usage();
107 			ifd = 0;
108 			break;
109 		case 'b':		/* Byte count. */
110 			if ((bytecnt = strtoq(optarg, &ep, 10)) <= 0 ||
111 			    (*ep != '\0' && *ep != 'k' && *ep != 'm'))
112 				errx(EX_USAGE,
113 				    "%s: illegal byte count", optarg);
114 			if (*ep == 'k')
115 				bytecnt *= 1024;
116 			else if (*ep == 'm')
117 				bytecnt *= 1048576;
118 			break;
119 		case 'p' :      /* pattern matching. */
120 			if (regcomp(&rgx, optarg, REG_EXTENDED|REG_NOSUB) != 0)
121 				errx(EX_USAGE, "%s: illegal regexp", optarg);
122 			pflag = 1;
123 			break;
124 		case 'l':		/* Line count. */
125 			if (numlines != 0)
126 				usage();
127 			if ((numlines = strtol(optarg, &ep, 10)) <= 0 || *ep)
128 				errx(EX_USAGE,
129 				    "%s: illegal line count", optarg);
130 			break;
131 		default:
132 			usage();
133 		}
134 	argv += optind;
135 	argc -= optind;
136 
137 	if (*argv != NULL)
138 		if (ifd == -1) {		/* Input file. */
139 			if ((ifd = open(*argv, O_RDONLY, 0)) < 0)
140 				err(EX_NOINPUT, "%s", *argv);
141 			++argv;
142 		}
143 	if (*argv != NULL)			/* File name prefix. */
144 		(void)strcpy(fname, *argv++);
145 	if (*argv != NULL)
146 		usage();
147 
148 	if (pflag && (numlines != 0 || bytecnt != 0))
149 		usage();
150 
151 	if (numlines == 0)
152 		numlines = DEFLINE;
153 	else if (bytecnt != 0)
154 		usage();
155 
156 	if (ifd == -1)				/* Stdin by default. */
157 		ifd = 0;
158 
159 	if (bytecnt) {
160 		split1();
161 		exit (0);
162 	}
163 	split2();
164 	if (pflag)
165 		regfree(&rgx);
166 	exit(0);
167 }
168 
169 /*
170  * split1 --
171  *	Split the input by bytes.
172  */
173 void
174 split1()
175 {
176 	size_t bcnt;
177 	char *C;
178 	int dist, len;
179 
180 	for (bcnt = 0;;)
181 		switch ((len = read(ifd, bfr, MAXBSIZE))) {
182 		case 0:
183 			exit(0);
184 		case -1:
185 			err(EX_IOERR, "read");
186 			/* NOTREACHED */
187 		default:
188 			if (!file_open)
189 				newfile();
190 			if (bcnt + len >= (u_int)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, bytecnt) != bytecnt)
200 						err(EX_IOERR, "write");
201 				}
202 				if (len != 0) {
203 					newfile();
204 					if (write(ofd, C, len) != len)
205 						err(EX_IOERR, "write");
206 				} else
207 					file_open = 0;
208 				bcnt = len;
209 			} else {
210 				bcnt += len;
211 				if (write(ofd, bfr, len) != len)
212 					err(EX_IOERR, "write");
213 			}
214 		}
215 }
216 
217 /*
218  * split2 --
219  *	Split the input by lines.
220  */
221 void
222 split2()
223 {
224 	long lcnt = 0;
225 	FILE *infp;
226 
227 	/* Stick a stream on top of input file descriptor */
228 	if ((infp = fdopen(ifd, "r")) == NULL)
229 		err(EX_NOINPUT, "fdopen");
230 
231 	/* Process input one line at a time */
232 	while (fgets(bfr, sizeof(bfr), infp) != NULL) {
233 		const int len = strlen(bfr);
234 
235 		/* If line is too long to deal with, just write it out */
236 		if (bfr[len - 1] != '\n')
237 			goto writeit;
238 
239 		/* Check if we need to start a new file */
240 		if (pflag) {
241 			regmatch_t pmatch;
242 
243 			pmatch.rm_so = 0;
244 			pmatch.rm_eo = len - 1;
245 			if (regexec(&rgx, bfr, 0, &pmatch, REG_STARTEND) == 0)
246 				newfile();
247 		} else if (lcnt++ == numlines) {
248 			newfile();
249 			lcnt = 1;
250 		}
251 
252 writeit:
253 		/* Open output file if needed */
254 		if (!file_open)
255 			newfile();
256 
257 		/* Write out line */
258 		if (write(ofd, bfr, len) != len)
259 			err(EX_IOERR, "write");
260 	}
261 
262 	/* EOF or error? */
263 	if (ferror(infp))
264 		err(EX_IOERR, "read");
265 	else
266 		exit(0);
267 }
268 
269 /*
270  * newfile --
271  *	Open a new output file.
272  */
273 void
274 newfile()
275 {
276 	static long fnum;
277 	static int defname;
278 	static char *fpnt;
279 
280 	if (ofd == -1) {
281 		if (fname[0] == '\0') {
282 			fname[0] = 'x';
283 			fpnt = fname + 1;
284 			defname = 1;
285 		} else {
286 			fpnt = fname + strlen(fname);
287 			defname = 0;
288 		}
289 		ofd = fileno(stdout);
290 	}
291 	/*
292 	 * Hack to increase max files; original code wandered through
293 	 * magic characters.  Maximum files is 3 * 26 * 26 == 2028
294 	 */
295 #define MAXFILES	676
296 	if (fnum == MAXFILES) {
297 		if (!defname || fname[0] == 'z')
298 			errx(EX_DATAERR, "too many files");
299 		++fname[0];
300 		fnum = 0;
301 	}
302 	fpnt[0] = fnum / 26 + 'a';
303 	fpnt[1] = fnum % 26 + 'a';
304 	++fnum;
305 	if (!freopen(fname, "w", stdout))
306 		err(EX_IOERR, "%s", fname);
307 	file_open = 1;
308 }
309 
310 static void
311 usage()
312 {
313 	(void)fprintf(stderr,
314 "usage: split [-b byte_count] [-l line_count] [-p pattern] [file [prefix]]\n");
315 	exit(EX_USAGE);
316 }
317