xref: /netbsd-src/usr.bin/split/split.c (revision deb6f0161a9109e7de9b519dc8dfb9478668dcdd)
1 /*	$NetBSD: split.c,v 1.27 2017/01/10 21:14:13 christos Exp $	*/
2 
3 /*
4  * Copyright (c) 1987, 1993, 1994
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 #include <sys/cdefs.h>
33 #ifndef lint
34 __COPYRIGHT("@(#) Copyright (c) 1987, 1993, 1994\
35  The Regents of the University of California.  All rights reserved.");
36 #endif /* not lint */
37 
38 #ifndef lint
39 #if 0
40 static char sccsid[] = "@(#)split.c	8.3 (Berkeley) 4/25/94";
41 #endif
42 __RCSID("$NetBSD: split.c,v 1.27 2017/01/10 21:14:13 christos Exp $");
43 #endif /* not lint */
44 
45 #include <sys/param.h>
46 #include <sys/stat.h>
47 
48 #include <ctype.h>
49 #include <err.h>
50 #include <errno.h>
51 #include <fcntl.h>
52 #include <stdio.h>
53 #include <stdlib.h>
54 #include <string.h>
55 #include <unistd.h>
56 
57 #define DEFLINE	1000		/* Default num lines per file. */
58 
59 static int file_open;		/* If a file open. */
60 static int ifd = STDIN_FILENO, ofd = -1; /* Input/output file descriptors. */
61 static char *fname;		/* File name prefix. */
62 static size_t sfxlen = 2;		/* suffix length. */
63 
64 static void newfile(void);
65 static void split1(off_t, int) __dead;
66 static void split2(off_t) __dead;
67 static void split3(off_t) __dead;
68 static void usage(void) __dead;
69 static size_t bigwrite(int, void const *, size_t);
70 
71 int
72 main(int argc, char *argv[])
73 {
74 	int ch;
75 	char *ep, *p;
76 	char const *base;
77 	off_t bytecnt = 0;	/* Byte count to split on. */
78 	off_t numlines = 0;	/* Line count to split on. */
79 	off_t chunks = 0;	/* Number of chunks to split into. */
80 
81 	while ((ch = getopt(argc, argv, "0123456789b:l:a:n:")) != -1)
82 		switch (ch) {
83 		case '0': case '1': case '2': case '3': case '4':
84 		case '5': case '6': case '7': case '8': case '9':
85 			/*
86 			 * Undocumented kludge: split was originally designed
87 			 * to take a number after a dash.
88 			 */
89 			if (numlines == 0) {
90 				p = argv[optind - 1];
91 				if (p[0] == '-' && p[1] == ch && !p[2])
92 					p++;
93 				else
94 					p = argv[optind] + 1;
95 				numlines = strtoull(p, &ep, 10);
96 				if (numlines == 0 || *ep != '\0')
97 					errx(1, "%s: illegal line count.", p);
98 			}
99 			break;
100 		case 'b':		/* Byte count. */
101 			if (!isdigit((unsigned char)optarg[0]) ||
102 			    (bytecnt = strtoull(optarg, &ep, 10)) == 0 ||
103 			    (*ep != '\0' && *ep != 'k' && *ep != 'm'))
104 				errx(1, "%s: illegal byte count.", optarg);
105 			if (*ep == 'k')
106 				bytecnt *= 1024;
107 			else if (*ep == 'm')
108 				bytecnt *= 1024 * 1024;
109 			break;
110 		case 'l':		/* Line count. */
111 			if (numlines != 0)
112 				usage();
113 			if (!isdigit((unsigned char)optarg[0]) ||
114 			    (numlines = strtoull(optarg, &ep, 10)) == 0 ||
115 			    *ep != '\0')
116 				errx(1, "%s: illegal line count.", optarg);
117 			break;
118 		case 'a':		/* Suffix length. */
119 			if (!isdigit((unsigned char)optarg[0]) ||
120 			    (sfxlen = (size_t)strtoul(optarg, &ep, 10)) == 0 ||
121 			    *ep != '\0')
122 				errx(1, "%s: illegal suffix length.", optarg);
123 			break;
124 		case 'n':		/* Chunks. */
125 			if (!isdigit((unsigned char)optarg[0]) ||
126 			    (chunks = (size_t)strtoul(optarg, &ep, 10)) == 0 ||
127 			    *ep != '\0')
128 				errx(1, "%s: illegal number of chunks.", optarg);
129 			break;
130 		default:
131 			usage();
132 		}
133 	argv += optind;
134 	argc -= optind;
135 
136 	if (*argv != NULL) {
137 		if (strcmp(*argv, "-") != 0 &&
138 		    (ifd = open(*argv, O_RDONLY, 0)) < 0)
139 			err(1, "%s", *argv);
140 		++argv;
141 	}
142 
143 
144 	base = (*argv != NULL) ? *argv++ : "x";
145 	if ((fname = malloc(strlen(base) + sfxlen + 1)) == NULL)
146 		err(EXIT_FAILURE, NULL);
147 	(void)strcpy(fname, base);		/* File name prefix. */
148 
149 	if (*argv != NULL)
150 		usage();
151 
152 	if (numlines == 0)
153 		numlines = DEFLINE;
154 	else if (bytecnt || chunks)
155 		usage();
156 
157 	if (bytecnt && chunks)
158 		usage();
159 
160 	if (bytecnt)
161 		split1(bytecnt, 0);
162 	else if (chunks)
163 		split3(chunks);
164 	else
165 		split2(numlines);
166 
167 	return 0;
168 }
169 
170 /*
171  * split1 --
172  *	Split the input by bytes.
173  */
174 static void
175 split1(off_t bytecnt, int maxcnt)
176 {
177 	off_t bcnt;
178 	ssize_t dist, len;
179 	char *C;
180 	char bfr[MAXBSIZE];
181 	int nfiles;
182 
183 	nfiles = 0;
184 
185 	for (bcnt = 0;;)
186 		switch (len = read(ifd, bfr, MAXBSIZE)) {
187 		case 0:
188 			exit(0);
189 			/* NOTREACHED */
190 		case -1:
191 			err(1, "read");
192 			/* NOTREACHED */
193 		default:
194 			if (!file_open) {
195 				if (!maxcnt || (nfiles < maxcnt)) {
196 					newfile();
197 					nfiles++;
198 					file_open = 1;
199 				}
200 			}
201 			if (bcnt + len >= bytecnt) {
202 				/* LINTED: bytecnt - bcnt <= len */
203 				dist = bytecnt - bcnt;
204 				if (bigwrite(ofd, bfr, dist) != (size_t)dist)
205 					err(1, "write");
206 				len -= dist;
207 				for (C = bfr + dist; len >= bytecnt;
208 				    /* LINTED: bytecnt <= len */
209 				    len -= bytecnt, C += bytecnt) {
210 					if (!maxcnt || (nfiles < maxcnt)) {
211 						newfile();
212 						nfiles++;
213 					}
214 					/* LINTED: as above */
215 					if (bigwrite(ofd,
216 					    C, bytecnt) != (size_t)bytecnt)
217 						err(1, "write");
218 				}
219 				if (len) {
220 					if (!maxcnt || (nfiles < maxcnt)) {
221 						newfile();
222 						nfiles++;
223 					}
224 					/* LINTED: len >= 0 */
225 					if (bigwrite(ofd, C, len) != (size_t)len)
226 						err(1, "write");
227 				} else
228 					file_open = 0;
229 				bcnt = len;
230 			} else {
231 				bcnt += len;
232 				/* LINTED: len >= 0 */
233 				if (bigwrite(ofd, bfr, len) != (size_t)len)
234 					err(1, "write");
235 			}
236 		}
237 }
238 
239 /*
240  * split2 --
241  *	Split the input by lines.
242  */
243 static void
244 split2(off_t numlines)
245 {
246 	off_t lcnt;
247 	size_t bcnt;
248 	ssize_t len;
249 	char *Ce, *Cs;
250 	char bfr[MAXBSIZE];
251 
252 	for (lcnt = 0;;)
253 		switch (len = read(ifd, bfr, MAXBSIZE)) {
254 		case 0:
255 			exit(0);
256 			/* NOTREACHED */
257 		case -1:
258 			err(1, "read");
259 			/* NOTREACHED */
260 		default:
261 			if (!file_open) {
262 				newfile();
263 				file_open = 1;
264 			}
265 			for (Cs = Ce = bfr; len--; Ce++)
266 				if (*Ce == '\n' && ++lcnt == numlines) {
267 					bcnt = Ce - Cs + 1;
268 					if (bigwrite(ofd, Cs, bcnt) != (size_t)bcnt)
269 						err(1, "write");
270 					lcnt = 0;
271 					Cs = Ce + 1;
272 					if (len)
273 						newfile();
274 					else
275 						file_open = 0;
276 				}
277 			if (Cs < Ce) {
278 				bcnt = Ce - Cs;
279 				if (bigwrite(ofd, Cs, bcnt) != (size_t)bcnt)
280 					err(1, "write");
281 			}
282 		}
283 }
284 
285 /*
286  * split3 --
287  *	Split the input into specified number of chunks
288  */
289 static void
290 split3(off_t chunks)
291 {
292 	struct stat sb;
293 
294 	if (fstat(ifd, &sb) == -1) {
295 		err(1, "stat");
296 		/* NOTREACHED */
297 	}
298 
299 	if (chunks > sb.st_size) {
300 		errx(1, "can't split into more than %d files",
301 				(int)sb.st_size);
302 		/* NOTREACHED */
303 	}
304 
305 	split1(sb.st_size/chunks, chunks);
306 }
307 
308 /*
309  * newfile --
310  *	Open a new output file.
311  */
312 static void
313 newfile(void)
314 {
315 	static int fnum;
316 	static char *fpnt;
317 	int quot, i;
318 
319 	if (ofd == -1) {
320 		fpnt = fname + strlen(fname);
321 		fpnt[sfxlen] = '\0';
322 	} else if (close(ofd) != 0)
323 		err(1, "%s", fname);
324 
325 	quot = fnum;
326 	for (i = sfxlen - 1; i >= 0; i--) {
327 		fpnt[i] = quot % 26 + 'a';
328 		quot = quot / 26;
329 	}
330 	if (quot > 0)
331 		errx(1, "too many files.");
332 	++fnum;
333 	if ((ofd = open(fname, O_WRONLY | O_CREAT | O_TRUNC, DEFFILEMODE)) < 0)
334 		err(1, "%s", fname);
335 }
336 
337 static size_t
338 bigwrite(int fd, const void *buf, size_t len)
339 {
340 	const char *ptr = buf;
341 	size_t sofar = 0;
342 	ssize_t w;
343 
344 	while (len != 0) {
345 		if  ((w = write(fd, ptr, len)) == -1)
346 			return sofar;
347 		len -= w;
348 		ptr += w;
349 		sofar += w;
350 	}
351 	return sofar;
352 }
353 
354 
355 static void
356 usage(void)
357 {
358 	(void)fprintf(stderr,
359 "usage: %s [-b byte_count] [-l line_count] [-n chunk_count] [-a suffix_length] "
360 "[file [prefix]]\n", getprogname());
361 	exit(1);
362 }
363