Home | History | Annotate | Line # | Download | only in split
split.c revision 1.18
      1 /*	$NetBSD: split.c,v 1.18 2003/07/10 20:43:40 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.18 2003/07/10 20:43:40 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 = STDIN_FILENO, 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 	char const *base;
     80 	off_t bytecnt = 0;	/* Byte count to split on. */
     81 	off_t numlines = 0;	/* Line count to split on. */
     82 	size_t namelen;
     83 	long name_max;
     84 
     85 	while ((ch = getopt(argc, argv, "0123456789b:l:a:")) != -1)
     86 		switch (ch) {
     87 		case '0': case '1': case '2': case '3': case '4':
     88 		case '5': case '6': case '7': case '8': case '9':
     89 			/*
     90 			 * Undocumented kludge: split was originally designed
     91 			 * to take a number after a dash.
     92 			 */
     93 			if (numlines == 0) {
     94 				p = argv[optind - 1];
     95 				if (p[0] == '-' && p[1] == ch && !p[2])
     96 					p++;
     97 				else
     98 					p = argv[optind] + 1;
     99 				numlines = strtoull(p, &ep, 10);
    100 				if (numlines == 0 || *ep != '\0')
    101 					errx(1, "%s: illegal line count.", p);
    102 			}
    103 			break;
    104 		case 'b':		/* Byte count. */
    105 			if (!isdigit((unsigned char)optarg[0]) ||
    106 			    (bytecnt = strtoull(optarg, &ep, 10)) == 0 ||
    107 			    (*ep != '\0' && *ep != 'k' && *ep != 'm'))
    108 				errx(1, "%s: illegal byte count.", optarg);
    109 			if (*ep == 'k')
    110 				bytecnt *= 1024;
    111 			else if (*ep == 'm')
    112 				bytecnt *= 1024 * 1024;
    113 			break;
    114 		case 'l':		/* Line count. */
    115 			if (numlines != 0)
    116 				usage();
    117 			if (!isdigit((unsigned char)optarg[0]) ||
    118 			    (numlines = strtoull(optarg, &ep, 10)) == 0 ||
    119 			    *ep != '\0')
    120 				errx(1, "%s: illegal line count.", optarg);
    121 			break;
    122 		case 'a':		/* Suffix length. */
    123 			if (!isdigit((unsigned char)optarg[0]) ||
    124 			    (sfxlen = (size_t)strtoul(optarg, &ep, 10)) == 0 ||
    125 			    *ep != '\0')
    126 				errx(1, "%s: illegal suffix length.", optarg);
    127 			break;
    128 		default:
    129 			usage();
    130 		}
    131 	argv += optind;
    132 	argc -= optind;
    133 
    134 	if (*argv != NULL) {
    135 		if (strcmp(*argv, "-") != 0 &&
    136 		    (ifd = open(*argv, O_RDONLY, 0)) < 0)
    137 			err(1, "%s", *argv);
    138 		++argv;
    139 	}
    140 
    141 	errno = 0;
    142 	if ((name_max = pathconf(".", _PC_NAME_MAX)) == -1 &&
    143 	    errno != 0)
    144 		err(EXIT_FAILURE, "pathconf");
    145 
    146 	base = (*argv != NULL) ? *argv++ : "x";
    147 	namelen = strlen(base) + sfxlen;
    148 	if (name_max != -1 && namelen > name_max)
    149 		errx(EXIT_FAILURE, "Output file name too long");
    150 	if ((fname = malloc(namelen + 1)) == NULL)
    151 		err(EXIT_FAILURE, NULL);
    152 	(void)strcpy(fname, base);		/* File name prefix. */
    153 
    154 	if (*argv != NULL)
    155 		usage();
    156 
    157 	if (numlines == 0)
    158 		numlines = DEFLINE;
    159 	else if (bytecnt)
    160 		usage();
    161 
    162 	if (bytecnt)
    163 		split1(bytecnt);
    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)
    176 {
    177 	off_t bcnt;
    178 	ssize_t dist, len;
    179 	char *C;
    180 	char bfr[MAXBSIZE];
    181 
    182 	for (bcnt = 0;;)
    183 		switch (len = read(ifd, bfr, MAXBSIZE)) {
    184 		case 0:
    185 			exit(0);
    186 			/* NOTREACHED */
    187 		case -1:
    188 			err(1, "read");
    189 			/* NOTREACHED */
    190 		default:
    191 			if (!file_open) {
    192 				newfile();
    193 				file_open = 1;
    194 			}
    195 			if (bcnt + len >= bytecnt) {
    196 				/* LINTED: bytecnt - bcnt <= len */
    197 				dist = bytecnt - bcnt;
    198 				if (bigwrite(ofd, bfr, dist) != dist)
    199 					err(1, "write");
    200 				len -= dist;
    201 				for (C = bfr + dist; len >= bytecnt;
    202 				    /* LINTED: bytecnt <= len */
    203 				    len -= bytecnt, C += bytecnt) {
    204 					newfile();
    205 					/* LINTED: as above */
    206 					if (bigwrite(ofd,
    207 					    C, bytecnt) != bytecnt)
    208 						err(1, "write");
    209 				}
    210 				if (len) {
    211 					newfile();
    212 					/* LINTED: len >= 0 */
    213 					if (bigwrite(ofd, C, len) != len)
    214 						err(1, "write");
    215 				} else
    216 					file_open = 0;
    217 				bcnt = len;
    218 			} else {
    219 				bcnt += len;
    220 				/* LINTED: len >= 0 */
    221 				if (bigwrite(ofd, bfr, len) != len)
    222 					err(1, "write");
    223 			}
    224 		}
    225 }
    226 
    227 /*
    228  * split2 --
    229  *	Split the input by lines.
    230  */
    231 static void
    232 split2(off_t numlines)
    233 {
    234 	off_t lcnt;
    235 	size_t bcnt;
    236 	ssize_t len;
    237 	char *Ce, *Cs;
    238 	char bfr[MAXBSIZE];
    239 
    240 	for (lcnt = 0;;)
    241 		switch (len = read(ifd, bfr, MAXBSIZE)) {
    242 		case 0:
    243 			exit(0);
    244 			/* NOTREACHED */
    245 		case -1:
    246 			err(1, "read");
    247 			/* NOTREACHED */
    248 		default:
    249 			if (!file_open) {
    250 				newfile();
    251 				file_open = 1;
    252 			}
    253 			for (Cs = Ce = bfr; len--; Ce++)
    254 				if (*Ce == '\n' && ++lcnt == numlines) {
    255 					bcnt = Ce - Cs + 1;
    256 					if (bigwrite(ofd, Cs, bcnt) != bcnt)
    257 						err(1, "write");
    258 					lcnt = 0;
    259 					Cs = Ce + 1;
    260 					if (len)
    261 						newfile();
    262 					else
    263 						file_open = 0;
    264 				}
    265 			if (Cs < Ce) {
    266 				bcnt = Ce - Cs;
    267 				if (bigwrite(ofd, Cs, bcnt) != bcnt)
    268 					err(1, "write");
    269 			}
    270 		}
    271 }
    272 
    273 /*
    274  * newfile --
    275  *	Open a new output file.
    276  */
    277 static void
    278 newfile(void)
    279 {
    280 	static int fnum;
    281 	static char *fpnt;
    282 	int quot, i;
    283 
    284 	if (ofd == -1) {
    285 		fpnt = fname + strlen(fname);
    286 		fpnt[sfxlen] = '\0';
    287 	} else if (close(ofd) != 0)
    288 		err(1, "%s", fname);
    289 
    290 	quot = fnum;
    291 	for (i = sfxlen - 1; i >= 0; i--) {
    292 		fpnt[i] = quot % 26 + 'a';
    293 		quot = quot / 26;
    294 	}
    295 	if (quot > 0)
    296 		errx(1, "too many files.");
    297 	++fnum;
    298 	if ((ofd = open(fname, O_WRONLY | O_CREAT | O_TRUNC, DEFFILEMODE)) < 0)
    299 		err(1, "%s", fname);
    300 }
    301 
    302 static size_t
    303 bigwrite(int fd, const void *buf, size_t len)
    304 {
    305 	const char *ptr = buf;
    306 	size_t sofar = 0;
    307 	ssize_t w;
    308 
    309 	while (len != 0) {
    310 		if  ((w = write(fd, ptr, len)) == -1)
    311 			return sofar;
    312 		len -= w;
    313 		ptr += w;
    314 		sofar += w;
    315 	}
    316 	return sofar;
    317 }
    318 
    319 
    320 static void
    321 usage(void)
    322 {
    323 	(void)fprintf(stderr,
    324 "Usage: %s [-b byte_count] [-l line_count] [-a suffix_length] "
    325 "[file [prefix]]\n", getprogname());
    326 	exit(1);
    327 }
    328