xref: /freebsd/usr.bin/split/split.c (revision c002b33b6041366aa2ed197dd154a73a00550ad6)
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
35 static const 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
41 #if 0
42 static char sccsid[] = "@(#)split.c	8.2 (Berkeley) 4/16/94";
43 #endif
44 #endif /* not lint */
45 
46 #include <sys/param.h>
47 
48 #include <ctype.h>
49 #include <err.h>
50 #include <fcntl.h>
51 #include <stdio.h>
52 #include <stdlib.h>
53 #include <string.h>
54 #include <unistd.h>
55 
56 #define DEFLINE	1000			/* Default num lines per file. */
57 
58 long	 bytecnt;			/* Byte count to split on. */
59 long	 numlines;			/* Line count to split on. */
60 int	 file_open;			/* If a file open. */
61 int	 ifd = -1, ofd = -1;		/* Input/output file descriptors. */
62 char	 bfr[MAXBSIZE];			/* I/O buffer. */
63 char	 fname[MAXPATHLEN];		/* File name prefix. */
64 
65 void newfile __P((void));
66 void split1 __P((void));
67 void split2 __P((void));
68 static void usage __P((void));
69 
70 int
71 main(argc, argv)
72 	int argc;
73 	char *argv[];
74 {
75 	int ch;
76 	char *ep, *p;
77 
78 	while ((ch = getopt(argc, argv, "-0123456789b:l:")) != -1)
79 		switch (ch) {
80 		case '0': case '1': case '2': case '3': case '4':
81 		case '5': case '6': case '7': case '8': case '9':
82 			/*
83 			 * Undocumented kludge: split was originally designed
84 			 * to take a number after a dash.
85 			 */
86 			if (numlines == 0) {
87 				p = argv[optind - 1];
88 				if (p[0] == '-' && p[1] == ch && !p[2])
89 					numlines = strtol(++p, &ep, 10);
90 				else
91 					numlines =
92 					    strtol(argv[optind] + 1, &ep, 10);
93 				if (numlines <= 0 || *ep)
94 					errx(1, "%s: illegal line count", optarg);
95 			}
96 			break;
97 		case '-':		/* Undocumented: historic stdin flag. */
98 			if (ifd != -1)
99 				usage();
100 			ifd = 0;
101 			break;
102 		case 'b':		/* Byte count. */
103 			if ((bytecnt = strtol(optarg, &ep, 10)) <= 0 ||
104 			    (*ep != '\0' && *ep != 'k' && *ep != 'm'))
105 				errx(1, "%s: illegal byte count", optarg);
106 			if (*ep == 'k')
107 				bytecnt *= 1024;
108 			else if (*ep == 'm')
109 				bytecnt *= 1048576;
110 			break;
111 		case 'l':		/* Line count. */
112 			if (numlines != 0)
113 				usage();
114 			if ((numlines = strtol(optarg, &ep, 10)) <= 0 || *ep)
115 				errx(1, "%s: illegal line count", optarg);
116 			break;
117 		default:
118 			usage();
119 		}
120 	argv += optind;
121 	argc -= optind;
122 
123 	if (*argv != NULL)
124 		if (ifd == -1) {		/* Input file. */
125 			if ((ifd = open(*argv, O_RDONLY, 0)) < 0)
126 				err(1, "%s", *argv);
127 			++argv;
128 		}
129 	if (*argv != NULL)			/* File name prefix. */
130 		(void)strcpy(fname, *argv++);
131 	if (*argv != NULL)
132 		usage();
133 
134 	if (numlines == 0)
135 		numlines = DEFLINE;
136 	else if (bytecnt)
137 		usage();
138 
139 	if (ifd == -1)				/* Stdin by default. */
140 		ifd = 0;
141 
142 	if (bytecnt) {
143 		split1();
144 		exit (0);
145 	}
146 	split2();
147 	exit(0);
148 }
149 
150 /*
151  * split1 --
152  *	Split the input by bytes.
153  */
154 void
155 split1()
156 {
157 	long bcnt;
158 	int dist, len;
159 	char *C;
160 
161 	for (bcnt = 0;;)
162 		switch (len = read(ifd, bfr, MAXBSIZE)) {
163 		case 0:
164 			exit(0);
165 		case -1:
166 			err(1, "read");
167 			/* NOTREACHED */
168 		default:
169 			if (!file_open) {
170 				newfile();
171 				file_open = 1;
172 			}
173 			if (bcnt + len >= bytecnt) {
174 				dist = bytecnt - bcnt;
175 				if (write(ofd, bfr, dist) != dist)
176 					err(1, "write");
177 				len -= dist;
178 				for (C = bfr + dist; len >= bytecnt;
179 				    len -= bytecnt, C += bytecnt) {
180 					newfile();
181 					if (write(ofd,
182 					    C, (int)bytecnt) != bytecnt)
183 						err(1, "write");
184 				}
185 				if (len) {
186 					newfile();
187 					if (write(ofd, C, len) != len)
188 						err(1, "write");
189 				} else
190 					file_open = 0;
191 				bcnt = len;
192 			} else {
193 				bcnt += len;
194 				if (write(ofd, bfr, len) != len)
195 					err(1, "write");
196 			}
197 		}
198 }
199 
200 /*
201  * split2 --
202  *	Split the input by lines.
203  */
204 void
205 split2()
206 {
207 	long lcnt;
208 	int len, bcnt;
209 	char *Ce, *Cs;
210 
211 	for (lcnt = 0;;)
212 		switch (len = read(ifd, bfr, MAXBSIZE)) {
213 		case 0:
214 			exit(0);
215 		case -1:
216 			err(1, "read");
217 			/* NOTREACHED */
218 		default:
219 			if (!file_open) {
220 				newfile();
221 				file_open = 1;
222 			}
223 			for (Cs = Ce = bfr; len--; Ce++)
224 				if (*Ce == '\n' && ++lcnt == numlines) {
225 					bcnt = Ce - Cs + 1;
226 					if (write(ofd, Cs, bcnt) != bcnt)
227 						err(1, "write");
228 					lcnt = 0;
229 					Cs = Ce + 1;
230 					if (len)
231 						newfile();
232 					else
233 						file_open = 0;
234 				}
235 			if (Cs < Ce) {
236 				bcnt = Ce - Cs;
237 				if (write(ofd, Cs, bcnt) != bcnt)
238 					err(1, "write");
239 			}
240 		}
241 }
242 
243 /*
244  * newfile --
245  *	Open a new output file.
246  */
247 void
248 newfile()
249 {
250 	static long fnum;
251 	static int defname;
252 	static char *fpnt;
253 
254 	if (ofd == -1) {
255 		if (fname[0] == '\0') {
256 			fname[0] = 'x';
257 			fpnt = fname + 1;
258 			defname = 1;
259 		} else {
260 			fpnt = fname + strlen(fname);
261 			defname = 0;
262 		}
263 		ofd = fileno(stdout);
264 	}
265 	/*
266 	 * Hack to increase max files; original code wandered through
267 	 * magic characters.  Maximum files is 3 * 26 * 26 == 2028
268 	 */
269 #define MAXFILES	676
270 	if (fnum == MAXFILES) {
271 		if (!defname || fname[0] == 'z')
272 			errx(1, "too many files");
273 		++fname[0];
274 		fnum = 0;
275 	}
276 	fpnt[0] = fnum / 26 + 'a';
277 	fpnt[1] = fnum % 26 + 'a';
278 	++fnum;
279 	if (!freopen(fname, "w", stdout))
280 		err(1, "%s", fname);
281 }
282 
283 static void
284 usage()
285 {
286 	(void)fprintf(stderr,
287 "usage: split [-b byte_count] [-l line_count] [file [prefix]]\n");
288 	exit(1);
289 }
290