Home | History | Annotate | Line # | Download | only in split
split.c revision 1.11
      1 /*	$NetBSD: split.c,v 1.11 2003/06/10 16:57:05 bjh21 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. All advertising materials mentioning features or use of this software
     16  *    must display the following acknowledgement:
     17  *	This product includes software developed by the University of
     18  *	California, Berkeley and its contributors.
     19  * 4. Neither the name of the University nor the names of its contributors
     20  *    may be used to endorse or promote products derived from this software
     21  *    without specific prior written permission.
     22  *
     23  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     33  * SUCH DAMAGE.
     34  */
     35 
     36 #include <sys/cdefs.h>
     37 #ifndef lint
     38 __COPYRIGHT("@(#) Copyright (c) 1987, 1993, 1994\n\
     39 	The Regents of the University of California.  All rights reserved.\n");
     40 #endif /* not lint */
     41 
     42 #ifndef lint
     43 #if 0
     44 static char sccsid[] = "@(#)split.c	8.3 (Berkeley) 4/25/94";
     45 #endif
     46 __RCSID("$NetBSD: split.c,v 1.11 2003/06/10 16:57:05 bjh21 Exp $");
     47 #endif /* not lint */
     48 
     49 #include <sys/param.h>
     50 
     51 #include <ctype.h>
     52 #include <err.h>
     53 #include <fcntl.h>
     54 #include <stdio.h>
     55 #include <stdlib.h>
     56 #include <string.h>
     57 #include <unistd.h>
     58 
     59 #define DEFLINE	1000		/* Default num lines per file. */
     60 
     61 static int file_open;		/* If a file open. */
     62 static int ifd = -1, ofd = -1;	/* Input/output file descriptors. */
     63 static char fname[MAXPATHLEN];	/* File name prefix. */
     64 static int sfxlen = 2;		/* suffix length. */
     65 
     66 int  main(int, char **);
     67 static void newfile(void);
     68 static void split1(unsigned long long);
     69 static void split2(unsigned long long);
     70 static void usage(void) __attribute__((__noreturn__));
     71 static unsigned long long bigwrite __P((int, const void *, unsigned long long));
     72 
     73 int
     74 main(int argc, char *argv[])
     75 {
     76 	int ch;
     77 	char *ep, *p;
     78 	unsigned long long bytecnt = 0;	/* Byte count to split on. */
     79 	unsigned long long numlines = 0;/* Line count to split on. */
     80 
     81 	while ((ch = getopt(argc, argv, "-0123456789b:l:a:")) != -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 					numlines = strtol(++p, &ep, 10);
     93 				else
     94 					numlines =
     95 					    strtol(argv[optind] + 1, &ep, 10);
     96 				if (numlines <= 0 || *ep)
     97 					errx(1,
     98 					    "%s: illegal line count.", optarg);
     99 			}
    100 			break;
    101 		case '-':		/* stdin flag. */
    102 			if (ifd != -1)
    103 				usage();
    104 			ifd = 0;
    105 			break;
    106 		case 'b':		/* Byte count. */
    107 			if ((bytecnt = strtoull(optarg, &ep, 10)) <= 0 ||
    108 			    (*ep != '\0' && *ep != 'k' && *ep != 'm'))
    109 				errx(1, "%s: illegal byte count.", optarg);
    110 			if (*ep == 'k')
    111 				bytecnt *= 1024;
    112 			else if (*ep == 'm')
    113 				bytecnt *= 1024 * 1024;
    114 			break;
    115 		case 'l':		/* Line count. */
    116 			if (numlines != 0)
    117 				usage();
    118 			if ((numlines = strtoull(optarg, &ep, 10)) <= 0 || *ep)
    119 				errx(1, "%s: illegal line count.", optarg);
    120 			break;
    121 		case 'a': /* Suffix length. */
    122 			if ((sfxlen = strtol(optarg, &ep, 10)) <= 0 || *ep)
    123 				errx(1, "%s: illegal suffix length.", optarg);
    124 			break;
    125 		default:
    126 			usage();
    127 		}
    128 	argv += optind;
    129 	argc -= optind;
    130 
    131 	if (*argv != NULL)
    132 		if (ifd == -1) {		/* Input file. */
    133 			if (strcmp(*argv, "-") == 0)
    134 				ifd = STDIN_FILENO;
    135 			else if ((ifd = open(*argv, O_RDONLY, 0)) < 0)
    136 				err(1, "%s", *argv);
    137 			++argv;
    138 		}
    139 
    140 	if (*argv != NULL) {
    141 		if (strlen(*argv) + sfxlen > NAME_MAX)
    142 			errx(EXIT_FAILURE, "Output file name too long");
    143 		(void)strcpy(fname, *argv++);		/* File name prefix. */
    144 	} else {
    145 		if (1 + sfxlen > NAME_MAX)
    146 			errx(EXIT_FAILURE, "Output file name too long");
    147 	}
    148 
    149 	if (*argv != NULL)
    150 		usage();
    151 
    152 	if (numlines == 0)
    153 		numlines = DEFLINE;
    154 	else if (bytecnt)
    155 		usage();
    156 
    157 	if (ifd == -1)				/* Stdin by default. */
    158 		ifd = 0;
    159 
    160 	if (bytecnt) {
    161 		split1(bytecnt);
    162 	} else {
    163 		split2(numlines);
    164 	}
    165 	return 0;
    166 }
    167 
    168 /*
    169  * split1 --
    170  *	Split the input by bytes.
    171  */
    172 static void
    173 split1(unsigned long long bytecnt)
    174 {
    175 	unsigned long long bcnt, dist;
    176 	ssize_t len;
    177 	char *C;
    178 	char bfr[MAXBSIZE];
    179 
    180 	for (bcnt = 0;;)
    181 		switch (len = read(ifd, bfr, MAXBSIZE)) {
    182 		case 0:
    183 			exit(0);
    184 		case -1:
    185 			err(1, "read");
    186 			/* NOTREACHED */
    187 		default:
    188 			if (!file_open) {
    189 				newfile();
    190 				file_open = 1;
    191 			}
    192 			if (bcnt + len >= bytecnt) {
    193 				dist = bytecnt - bcnt;
    194 				if (bigwrite(ofd, bfr, dist) != dist)
    195 					err(1, "write");
    196 				len -= dist;
    197 				for (C = bfr + dist; len >= bytecnt;
    198 				    len -= bytecnt, C += bytecnt) {
    199 					newfile();
    200 					if (bigwrite(ofd,
    201 					    C, (int)bytecnt) != bytecnt)
    202 						err(1, "write");
    203 				}
    204 				if (len) {
    205 					newfile();
    206 					if (bigwrite(ofd, C, len) != len)
    207 						err(1, "write");
    208 				} else
    209 					file_open = 0;
    210 				bcnt = len;
    211 			} else {
    212 				bcnt += len;
    213 				if (bigwrite(ofd, bfr, len) != len)
    214 					err(1, "write");
    215 			}
    216 		}
    217 }
    218 
    219 /*
    220  * split2 --
    221  *	Split the input by lines.
    222  */
    223 static void
    224 split2(unsigned long long numlines)
    225 {
    226 	unsigned long long lcnt, bcnt;
    227 	ssize_t len;
    228 	char *Ce, *Cs;
    229 	char bfr[MAXBSIZE];
    230 
    231 	for (lcnt = 0;;)
    232 		switch (len = read(ifd, bfr, MAXBSIZE)) {
    233 		case 0:
    234 			exit(0);
    235 		case -1:
    236 			err(1, "read");
    237 			/* NOTREACHED */
    238 		default:
    239 			if (!file_open) {
    240 				newfile();
    241 				file_open = 1;
    242 			}
    243 			for (Cs = Ce = bfr; len--; Ce++)
    244 				if (*Ce == '\n' && ++lcnt == numlines) {
    245 					bcnt = Ce - Cs + 1;
    246 					if (bigwrite(ofd, Cs, bcnt) != bcnt)
    247 						err(1, "write");
    248 					lcnt = 0;
    249 					Cs = Ce + 1;
    250 					if (len)
    251 						newfile();
    252 					else
    253 						file_open = 0;
    254 				}
    255 			if (Cs < Ce) {
    256 				bcnt = Ce - Cs;
    257 				if (bigwrite(ofd, Cs, bcnt) != bcnt)
    258 					err(1, "write");
    259 			}
    260 		}
    261 }
    262 
    263 /*
    264  * newfile --
    265  *	Open a new output file.
    266  */
    267 static void
    268 newfile(void)
    269 {
    270 	static int fnum;
    271 	static int defname;
    272 	static char *fpnt;
    273 	int quot, i;
    274 
    275 	if (ofd == -1) {
    276 		if (fname[0] == '\0') {
    277 			fname[0] = 'x';
    278 			fpnt = fname + 1;
    279 			defname = 1;
    280 		} else {
    281 			fpnt = fname + strlen(fname);
    282 			defname = 0;
    283 		}
    284 		ofd = fileno(stdout);
    285 	}
    286 	/*
    287 	 * Hack to increase max files; original code wandered through
    288 	 * magic characters.  Maximum files is 3 * 26 * 26 == 2028
    289 	 */
    290 	fpnt[sfxlen] = '\0';
    291 	quot = fnum;
    292 	for (i = sfxlen - 1; i >= 0; i--) {
    293 		fpnt[i] = quot % 26 + 'a';
    294 		quot = quot / 26;
    295 	}
    296 	if (quot > 0) {
    297 		if (!defname || fname[0] == 'z')
    298 			errx(1, "too many files.");
    299 		++fname[0];
    300 		fnum = 0;
    301 	}
    302 	++fnum;
    303 	if (!freopen(fname, "w", stdout))
    304 		err(1, "%s", fname);
    305 }
    306 
    307 static unsigned long long
    308 bigwrite(int fd, const void *buf, unsigned long long len)
    309 {
    310 	const char *ptr = buf;
    311 	unsigned long long sofar = 0;
    312 
    313 	while (len != 0) {
    314 		ssize_t w, nw = (len > INT_MAX) ? INT_MAX : (ssize_t)len;
    315 		if  ((w = write(fd, ptr, nw)) == -1)
    316 			return sofar;
    317 		len -= w;
    318 		ptr += w;
    319 		sofar += w;
    320 	}
    321 	return sofar;
    322 }
    323 
    324 
    325 static void
    326 usage(void)
    327 {
    328 	(void)fprintf(stderr,
    329 "Usage: %s [-b byte_count] [-l line_count] [-a suffix_length] "
    330 "[file [prefix]]\n", getprogname());
    331 	exit(1);
    332 }
    333