Home | History | Annotate | Line # | Download | only in split
split.c revision 1.14
      1 /*	$NetBSD: split.c,v 1.14 2003/06/26 22:49:53 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.14 2003/06/26 22:49:53 bjh21 Exp $");
     47 #endif /* not lint */
     48 
     49 #include <sys/param.h>
     50 
     51 #include <ctype.h>
     52 #include <err.h>
     53 #include <errno.h>
     54 #include <fcntl.h>
     55 #include <stdio.h>
     56 #include <stdlib.h>
     57 #include <string.h>
     58 #include <unistd.h>
     59 
     60 #define DEFLINE	1000		/* Default num lines per file. */
     61 
     62 static int file_open;		/* If a file open. */
     63 static int ifd = -1, ofd = -1;	/* Input/output file descriptors. */
     64 static char *fname;		/* File name prefix. */
     65 static size_t sfxlen = 2;		/* suffix length. */
     66 
     67 int  main(int, char **);
     68 static void newfile(void);
     69 static void split1(off_t);
     70 static void split2(off_t);
     71 static void usage(void) __attribute__((__noreturn__));
     72 static size_t bigwrite(int, void const *, size_t);
     73 
     74 int
     75 main(int argc, char *argv[])
     76 {
     77 	int ch;
     78 	char *ep, *p;
     79 	off_t bytecnt = 0;	/* Byte count to split on. */
     80 	off_t numlines = 0;	/* Line count to split on. */
     81 	size_t namelen;
     82 	long name_max;
     83 
     84 	while ((ch = getopt(argc, argv, "-0123456789b:l:a:")) != -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 					p++;
     96 				else
     97 					p = argv[optind] + 1;
     98 				numlines = strtoull(p, &ep, 10);
     99 				if (numlines == 0 || *ep != '\0')
    100 					errx(1, "%s: illegal line count.", p);
    101 			}
    102 			break;
    103 		case '-':		/* stdin flag. */
    104 			if (ifd != -1)
    105 				usage();
    106 			ifd = 0;
    107 			break;
    108 		case 'b':		/* Byte count. */
    109 			if (!isdigit((unsigned char)optarg[0]) ||
    110 			    (bytecnt = strtoull(optarg, &ep, 10)) == 0 ||
    111 			    (*ep != '\0' && *ep != 'k' && *ep != 'm'))
    112 				errx(1, "%s: illegal byte count.", optarg);
    113 			if (*ep == 'k')
    114 				bytecnt *= 1024;
    115 			else if (*ep == 'm')
    116 				bytecnt *= 1024 * 1024;
    117 			break;
    118 		case 'l':		/* Line count. */
    119 			if (numlines != 0)
    120 				usage();
    121 			if (!isdigit((unsigned char)optarg[0]) ||
    122 			    (numlines = strtoull(optarg, &ep, 10)) == 0 ||
    123 			    *ep != '\0')
    124 				errx(1, "%s: illegal line count.", optarg);
    125 			break;
    126 		case 'a':		/* Suffix length. */
    127 			if (!isdigit((unsigned char)optarg[0]) ||
    128 			    (sfxlen = (size_t)strtoul(optarg, &ep, 10)) == 0 ||
    129 			    *ep != '\0')
    130 				errx(1, "%s: illegal suffix length.", optarg);
    131 			break;
    132 		default:
    133 			usage();
    134 		}
    135 	argv += optind;
    136 	argc -= optind;
    137 
    138 	if (*argv != NULL)
    139 		if (ifd == -1) {		/* Input file. */
    140 			if (strcmp(*argv, "-") == 0)
    141 				ifd = STDIN_FILENO;
    142 			else if ((ifd = open(*argv, O_RDONLY, 0)) < 0)
    143 				err(1, "%s", *argv);
    144 			++argv;
    145 		}
    146 
    147 	errno = 0;
    148 	if ((name_max = pathconf(".", _PC_NAME_MAX)) == -1 &&
    149 	    errno != 0)
    150 		err(EXIT_FAILURE, "pathconf");
    151 	if (*argv != NULL) {
    152 		namelen = strlen(*argv) + sfxlen;
    153 		if (name_max != -1 && namelen > name_max)
    154 			errx(EXIT_FAILURE, "Output file name too long");
    155 		if ((fname = malloc(namelen + 1)) == NULL)
    156 			err(EXIT_FAILURE, NULL);
    157 		(void)strcpy(fname, *argv++);		/* File name prefix. */
    158 	} else {
    159 		if (name_max != -1 && 1 + sfxlen > name_max)
    160 			errx(EXIT_FAILURE, "Output file name too long");
    161 		if ((fname = malloc(sfxlen + 2)) == NULL)
    162 			err(EXIT_FAILURE, NULL);
    163 		fname[0] = '\0';
    164 	}
    165 
    166 	if (*argv != NULL)
    167 		usage();
    168 
    169 	if (numlines == 0)
    170 		numlines = DEFLINE;
    171 	else if (bytecnt)
    172 		usage();
    173 
    174 	if (ifd == -1)				/* Stdin by default. */
    175 		ifd = 0;
    176 
    177 	if (bytecnt)
    178 		split1(bytecnt);
    179 	else
    180 		split2(numlines);
    181 
    182 	return 0;
    183 }
    184 
    185 /*
    186  * split1 --
    187  *	Split the input by bytes.
    188  */
    189 static void
    190 split1(off_t bytecnt)
    191 {
    192 	off_t bcnt;
    193 	ssize_t dist, len;
    194 	char *C;
    195 	char bfr[MAXBSIZE];
    196 
    197 	for (bcnt = 0;;)
    198 		switch (len = read(ifd, bfr, MAXBSIZE)) {
    199 		case 0:
    200 			exit(0);
    201 			/* NOTREACHED */
    202 		case -1:
    203 			err(1, "read");
    204 			/* NOTREACHED */
    205 		default:
    206 			if (!file_open) {
    207 				newfile();
    208 				file_open = 1;
    209 			}
    210 			if (bcnt + len >= bytecnt) {
    211 				/* LINTED: bytecnt - bcnt <= len */
    212 				dist = bytecnt - bcnt;
    213 				if (bigwrite(ofd, bfr, dist) != dist)
    214 					err(1, "write");
    215 				len -= dist;
    216 				for (C = bfr + dist; len >= bytecnt;
    217 				    /* LINTED: bytecnt <= len */
    218 				    len -= bytecnt, C += bytecnt) {
    219 					newfile();
    220 					/* LINTED: as above */
    221 					if (bigwrite(ofd,
    222 					    C, bytecnt) != bytecnt)
    223 						err(1, "write");
    224 				}
    225 				if (len) {
    226 					newfile();
    227 					/* LINTED: len >= 0 */
    228 					if (bigwrite(ofd, C, len) != len)
    229 						err(1, "write");
    230 				} else
    231 					file_open = 0;
    232 				bcnt = len;
    233 			} else {
    234 				bcnt += len;
    235 				/* LINTED: len >= 0 */
    236 				if (bigwrite(ofd, bfr, len) != len)
    237 					err(1, "write");
    238 			}
    239 		}
    240 }
    241 
    242 /*
    243  * split2 --
    244  *	Split the input by lines.
    245  */
    246 static void
    247 split2(off_t numlines)
    248 {
    249 	off_t lcnt;
    250 	size_t bcnt;
    251 	ssize_t len;
    252 	char *Ce, *Cs;
    253 	char bfr[MAXBSIZE];
    254 
    255 	for (lcnt = 0;;)
    256 		switch (len = read(ifd, bfr, MAXBSIZE)) {
    257 		case 0:
    258 			exit(0);
    259 			/* NOTREACHED */
    260 		case -1:
    261 			err(1, "read");
    262 			/* NOTREACHED */
    263 		default:
    264 			if (!file_open) {
    265 				newfile();
    266 				file_open = 1;
    267 			}
    268 			for (Cs = Ce = bfr; len--; Ce++)
    269 				if (*Ce == '\n' && ++lcnt == numlines) {
    270 					bcnt = Ce - Cs + 1;
    271 					if (bigwrite(ofd, Cs, bcnt) != bcnt)
    272 						err(1, "write");
    273 					lcnt = 0;
    274 					Cs = Ce + 1;
    275 					if (len)
    276 						newfile();
    277 					else
    278 						file_open = 0;
    279 				}
    280 			if (Cs < Ce) {
    281 				bcnt = Ce - Cs;
    282 				if (bigwrite(ofd, Cs, bcnt) != bcnt)
    283 					err(1, "write");
    284 			}
    285 		}
    286 }
    287 
    288 /*
    289  * newfile --
    290  *	Open a new output file.
    291  */
    292 static void
    293 newfile(void)
    294 {
    295 	static int fnum;
    296 	static int defname;
    297 	static char *fpnt;
    298 	int quot, i;
    299 
    300 	if (ofd == -1) {
    301 		if (fname[0] == '\0') {
    302 			fname[0] = 'x';
    303 			fpnt = fname + 1;
    304 			defname = 1;
    305 		} else {
    306 			fpnt = fname + strlen(fname);
    307 			defname = 0;
    308 		}
    309 		ofd = fileno(stdout);
    310 	}
    311 	/*
    312 	 * Hack to increase max files; original code wandered through
    313 	 * magic characters.  Maximum files is 3 * 26 * 26 == 2028
    314 	 */
    315 	fpnt[sfxlen] = '\0';
    316 	quot = fnum;
    317 	for (i = sfxlen - 1; i >= 0; i--) {
    318 		fpnt[i] = quot % 26 + 'a';
    319 		quot = quot / 26;
    320 	}
    321 	if (quot > 0) {
    322 		if (!defname || fname[0] == 'z')
    323 			errx(1, "too many files.");
    324 		++fname[0];
    325 		fnum = 0;
    326 	}
    327 	++fnum;
    328 	if (!freopen(fname, "w", stdout))
    329 		err(1, "%s", fname);
    330 }
    331 
    332 static size_t
    333 bigwrite(int fd, const void *buf, size_t len)
    334 {
    335 	const char *ptr = buf;
    336 	size_t sofar = 0;
    337 	ssize_t w;
    338 
    339 	while (len != 0) {
    340 		if  ((w = write(fd, ptr, len)) == -1)
    341 			return sofar;
    342 		len -= w;
    343 		ptr += w;
    344 		sofar += w;
    345 	}
    346 	return sofar;
    347 }
    348 
    349 
    350 static void
    351 usage(void)
    352 {
    353 	(void)fprintf(stderr,
    354 "Usage: %s [-b byte_count] [-l line_count] [-a suffix_length] "
    355 "[file [prefix]]\n", getprogname());
    356 	exit(1);
    357 }
    358