Subject: Re: bin/34599: csplit(1) utility port
To: None <gnats-admin@netbsd.org, netbsd-bugs@netbsd.org, unex@linija.org>
From: Mindaugas <unex@linija.org>
List: netbsd-bugs
Date: 09/25/2006 01:05:04
The following reply was made to PR bin/34599; it has been noted by GNATS.

From: Mindaugas <unex@linija.org>
To: gnats-bugs@NetBSD.org
Cc: 
Subject: Re: bin/34599: csplit(1) utility port
Date: Mon, 25 Sep 2006 04:03:27 +0300

 This is a multi-part message in MIME format.
 
 --Multipart=_Mon__25_Sep_2006_04_03_27_+0300_L9jqCbwt3wbuiU4C
 Content-Type: text/plain; charset=US-ASCII
 Content-Transfer-Encoding: 7bit
 
 Here is an attached files. Should be contents of src/usr.bin/csplit .
 
 -- 
 Best regards,
 Mindaugas
 
 --Multipart=_Mon__25_Sep_2006_04_03_27_+0300_L9jqCbwt3wbuiU4C
 Content-Type: application/octet-stream;
  name="Makefile"
 Content-Disposition: attachment;
  filename="Makefile"
 Content-Transfer-Encoding: quoted-printable
 
 #	$NetBSD$
 
 PROG=3D	csplit
 
 .include <bsd.prog.mk>
 
 --Multipart=_Mon__25_Sep_2006_04_03_27_+0300_L9jqCbwt3wbuiU4C
 Content-Type: application/octet-stream;
  name="csplit.1"
 Content-Disposition: attachment;
  filename="csplit.1"
 Content-Transfer-Encoding: quoted-printable
 
 .\"	$NetBSD$
 .\"
 .\" Copyright (c) 2002 Tim J. Robbins.
 .\" All rights reserved.
 .\"
 .\" Redistribution and use in source and binary forms, with or without
 .\" modification, are permitted provided that the following conditions
 .\" are met:
 .\" 1. Redistributions of source code must retain the above copyright
 .\"    notice, this list of conditions and the following disclaimer.
 .\" 2. Redistributions in binary form must reproduce the above copyright
 .\"    notice, this list of conditions and the following disclaimer in the
 .\"    documentation and/or other materials provided with the distribution.
 .\"
 .\" THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
 OSE
 .\" ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
 IAL
 .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
 ICT
 .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
 AY
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
 .\" $FreeBSD: src/usr.bin/csplit/csplit.1,v 1.11 2005/01/25 22:29:51 tjr Ex=
 p $
 .\"
 .Dd January 26, 2005
 .Dt CSPLIT 1
 .Os
 .Sh NAME
 .Nm csplit
 .Nd split files based on context
 .Sh SYNOPSIS
 .Nm
 .Op Fl ks
 .Op Fl f Ar prefix
 .Op Fl n Ar number
 .Ar file args ...
 .Sh DESCRIPTION
 The
 .Nm
 utility splits
 .Ar file
 into pieces using the patterns
 .Ar args .
 If
 .Ar file
 is
 a dash
 .Pq Sq - ,
 .Nm
 reads from standard input.
 .Pp
 The options are as follows:
 .Bl -tag -width indent
 .It Fl f Ar prefix
 Give created files names beginning with
 .Ar prefix .
 The default is
 .Dq xx .
 .It Fl k
 Do not remove output files if an error occurs or a
 .Dv HUP ,
 .Dv INT ,
 or
 .Dv TERM
 signal is received.
 .It Fl n Ar number
 Use
 .Ar number
 of decimal digits after the
 .Ar prefix
 to form the file name.
 The default is 2.
 .It Fl s
 Do not write the size of each output file to standard output as it is
 created.
 .El
 .Pp
 The
 .Ar args
 operands may be a combination of the following patterns:
 .Bl -tag -width indent
 .It Xo
 .Sm off
 .No / Ar regexp No /
 .Op Oo Cm + | - Oc Ar offset
 .Sm on
 .Xc
 Create a file containing the input from the current line to (but not includ=
 ing)
 the next line matching the given basic regular expression.
 An optional
 .Ar offset
 from the line that matched may be specified.
 .It Xo
 .Sm off
 .No % Ar regexp No %
 .Op Oo Cm + | - Oc Ar offset
 .Sm on
 .Xc
 Same as above but a file is not created for the output.
 .It Ar line_no
 Create containing the input from the current line to (but not including)
 the specified line number.
 .It { Ns Ar num Ns }
 Repeat the previous pattern the specified number of times.
 If it follows a line number pattern, a new file will be created for each
 .Ar line_no
 lines,
 .Ar num
 times.
 The first line of the file is line number 1 for historic reasons.
 .El
 .Pp
 After all the patterns have been processed, the remaining input data
 (if there is any) will be written to a new file.
 .Pp
 Requesting to split at a line before the current line number or past the
 end of the file will result in an error.
 .Pp
 .Ex -std
 .Sh ENVIRONMENT
 The
 .Ev LANG , LC_ALL , LC_COLLATE ,
 and
 .Ev LC_CTYPE
 environment variables affect the execution of
 .Nm
 as described in
 .Xr environ 7 .
 .Sh EXAMPLES
 Split the
 .Xr mdoc 7
 file
 .Pa foo.1
 into one file for each section (up to 20):
 .Pp
 .Dl "$ csplit -k foo.1 '%^\e.Sh%' '/^\e.Sh/' '{20}'"
 .Pp
 Split standard input after the first 99 lines and every 100 lines thereafte=
 r:
 .Pp
 .Dl "$ csplit -k - 100 '{19}'"
 .Sh SEE ALSO
 .Xr sed 1 ,
 .Xr split 1 ,
 .Xr re_format 7
 .Sh STANDARDS
 The
 .Nm
 utility conforms to
 .St -p1003.1-2004 .
 .Sh HISTORY
 A
 .Nm
 command appeared in PWB UNIX.
 .Sh BUGS
 Input lines are limited to
 .Dv LINE_MAX
 (2048) bytes in length.
 
 --Multipart=_Mon__25_Sep_2006_04_03_27_+0300_L9jqCbwt3wbuiU4C
 Content-Type: application/octet-stream;
  name="csplit.c"
 Content-Disposition: attachment;
  filename="csplit.c"
 Content-Transfer-Encoding: quoted-printable
 
 /*	$NetBSD$	*/
 /*	$FreeBSD: src/usr.bin/csplit/csplit.c,v 1.9 2004/03/22 11:15:03 tjr Exp =
 $	*/
 
 /*-
  * Copyright (c) 2002 Tim J. Robbins.
  * All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
  *
  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPO=
 SE
  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTI=
 AL
  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRI=
 CT
  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  */
 
 /*
  * csplit -- split files based on context
  *
  * This utility splits its input into numbered output files by line number
  * or by a regular expression. Regular expression matches have an optional
  * offset with them, allowing the split to occur a specified number of
  * lines before or after the match.
  *
  * To handle negative offsets, we stop reading when the match occurs and
  * store the offset that the file should have been split at, then use
  * this output file as input until all the "overflowed" lines have been rea=
 d.
  * The file is then closed and truncated to the correct length.
  *
  * We assume that the output files can be seeked upon (ie. they cannot be
  * symlinks to named pipes or character devices), but make no such
  * assumption about the input.
  */
 
 #include <sys/cdefs.h>
 #ifndef lint
 __RCSID("$NetBSD$");
 #endif
 
 #include <sys/types.h>
 
 #include <ctype.h>
 #include <err.h>
 #include <errno.h>
 #include <limits.h>
 #include <locale.h>
 #include <regex.h>
 #include <signal.h>
 #include <stdint.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 #include <unistd.h>
 
 void	 cleanup(void);
 void	 do_lineno(const char *);
 void	 do_rexp(const char *);
 char	*getline(void);
 void	 handlesig(int);
 FILE	*newfile(void);
 void	 toomuch(FILE *, long);
 void	 usage(void);
 
 /*
  * Command line options
  */
 const char *prefix;		/* File name prefix */
 long	 sufflen;		/* Number of decimal digits for suffix */
 int	 sflag;			/* Suppress output of file names */
 int	 kflag;			/* Keep output if error occurs */
 
 /*
  * Other miscellaneous globals (XXX too many)
  */
 long	 lineno;		/* Current line number in input file */
 long	 reps;			/* Number of repetitions for this pattern */
 long	 nfiles;		/* Number of files output so far */
 long	 maxfiles;		/* Maximum number of files we can create */
 char	 currfile[PATH_MAX];	/* Current output file */
 const char *infn;		/* Name of the input file */
 FILE	*infile;		/* Input file handle */
 FILE	*overfile;		/* Overflow file for toomuch() */
 off_t	 truncofs;		/* Offset this file should be truncated at */
 int	 doclean;		/* Should cleanup() remove output? */
 
 int
 main(int argc, char *argv[])
 {
 	struct sigaction sa;
 	long i;
 	int ch;
 	const char *expr;
 	char *ep, *p;
 	FILE *ofp;
 
 	setlocale(LC_ALL, "");
 
 	kflag =3D sflag =3D 0;
 	prefix =3D "xx";
 	sufflen =3D 2;
 	while ((ch =3D getopt(argc, argv, "ksf:n:")) > 0) {
 		switch (ch) {
 		case 'f':
 			prefix =3D optarg;
 			break;
 		case 'k':
 			kflag =3D 1;
 			break;
 		case 'n':
 			errno =3D 0;
 			sufflen =3D strtol(optarg, &ep, 10);
 			if (sufflen <=3D 0 || *ep !=3D '\0' || errno !=3D 0)
 				errx(1, "%s: bad suffix length", optarg);
 			break;
 		case 's':
 			sflag =3D 1;
 			break;
 		default:
 			usage();
 			/*NOTREACHED*/
 		}
 	}
 
 	if (sufflen + strlen(prefix) >=3D PATH_MAX)
 		errx(1, "name too long");
 
 	argc -=3D optind;
 	argv +=3D optind;
 
 	if ((infn =3D *argv++) =3D=3D NULL)
 		usage();
 	if (strcmp(infn, "-") =3D=3D 0) {
 		infile =3D stdin;
 		infn =3D "stdin";
 	} else if ((infile =3D fopen(infn, "r")) =3D=3D NULL)
 		err(1, "%s", infn);
 
 	if (!kflag) {
 		doclean =3D 1;
 		atexit(cleanup);
 		sa.sa_flags =3D 0;
 		sa.sa_handler =3D handlesig;
 		sigemptyset(&sa.sa_mask);
 		sigaddset(&sa.sa_mask, SIGHUP);
 		sigaddset(&sa.sa_mask, SIGINT);
 		sigaddset(&sa.sa_mask, SIGTERM);
 		sigaction(SIGHUP, &sa, NULL);
 		sigaction(SIGINT, &sa, NULL);
 		sigaction(SIGTERM, &sa, NULL);
 	}
 
 	lineno =3D 0;
 	nfiles =3D 0;
 	truncofs =3D 0;
 	overfile =3D NULL;
 
 	/* Ensure 10^sufflen < LONG_MAX. */
 	for (maxfiles =3D 1, i =3D 0; i < sufflen; i++) {
 		if (maxfiles > LONG_MAX / 10)
 			errx(1, "%ld: suffix too long (limit %ld)",
 			    sufflen, i);
 		maxfiles *=3D 10;
 	}
 
 	/* Create files based on supplied patterns. */
 	while (nfiles < maxfiles - 1 && (expr =3D *argv++) !=3D NULL) {
 		/* Look ahead & see if this pattern has any repetitions. */
 		if (*argv !=3D NULL && **argv =3D=3D '{') {
 			errno =3D 0;
 			reps =3D strtol(*argv + 1, &ep, 10);
 			if (reps < 0 || *ep !=3D '}' || errno !=3D 0)
 				errx(1, "%s: bad repetition count", *argv + 1);
 			argv++;
 		} else
 			reps =3D 0;
 
 		if (*expr =3D=3D '/' || *expr =3D=3D '%') {
 			do
 				do_rexp(expr);
 			while (reps-- !=3D 0 && nfiles < maxfiles - 1);
 		} else if (isdigit((unsigned char)*expr))
 			do_lineno(expr);
 		else
 			errx(1, "%s: unrecognised pattern", expr);
 	}
 
 	/* Copy the rest into a new file. */
 	if (!feof(infile)) {
 		ofp =3D newfile();
 		while ((p =3D getline()) !=3D NULL && fputs(p, ofp) =3D=3D 0)
 			;
 		if (!sflag)
 			printf("%jd\n", (intmax_t)ftello(ofp));
 		if (fclose(ofp) !=3D 0)
 			err(1, "%s", currfile);
 	}
 
 	toomuch(NULL, 0);
 	doclean =3D 0;
 
 	return (0);
 }
 
 void
 usage(void)
 {
 
 	fprintf(stderr,
 "usage: csplit [-ks] [-f prefix] [-n number] file args ...\n");
 	exit(1);
 }
 
 void
 handlesig(int sig __unused)
 {
 	const char msg[] =3D "csplit: caught signal, cleaning up\n";
 
 	write(STDERR_FILENO, msg, sizeof(msg) - 1);
 	cleanup();
 	_exit(2);
 }
 
 /* Create a new output file. */
 FILE *
 newfile(void)
 {
 	FILE *fp;
 
 	if ((size_t)snprintf(currfile, sizeof(currfile), "%s%0*ld", prefix,
 	    (int)sufflen, nfiles) >=3D sizeof(currfile))
 		errx(1, "%s: %s", currfile, strerror(ENAMETOOLONG));
 	if ((fp =3D fopen(currfile, "w+")) =3D=3D NULL)
 		err(1, "%s", currfile);
 	nfiles++;
 
 	return (fp);
 }
 
 /* Remove partial output, called before exiting. */
 void
 cleanup(void)
 {
 	char fnbuf[PATH_MAX];
 	long i;
 
 	if (!doclean)
 		return;
 
 	/*
 	 * NOTE: One cannot portably assume to be able to call snprintf()
 	 * from inside a signal handler. It does, however, appear to be safe
 	 * to do on FreeBSD and NetBSD. The solution to this problem is worse
 	 * than the problem itself.
 	 */
 
 	for (i =3D 0; i < nfiles; i++) {
 		snprintf(fnbuf, sizeof(fnbuf), "%s%0*ld", prefix,
 		    (int)sufflen, i);
 		unlink(fnbuf);
 	}
 }
 
 /* Read a line from the input into a static buffer. */
 char *
 getline(void)
 {
 	static char lbuf[LINE_MAX];
 	FILE *src;
 
 	src =3D overfile !=3D NULL ? overfile : infile;
 
 again: if (fgets(lbuf, sizeof(lbuf), src) =3D=3D NULL) {
 		if (src =3D=3D overfile) {
 			src =3D infile;
 			goto again;
 		}
 		return (NULL);
 	}
 	if (ferror(src))
 		err(1, "%s", infn);
 	lineno++;
 
 	return (lbuf);
 }
 
 /* Conceptually rewind the input (as obtained by getline()) back `n' lines.=
  */
 void
 toomuch(FILE *ofp, long n)
 {
 	char buf[BUFSIZ];
 	size_t i, nread;
 
 	if (overfile !=3D NULL) {
 		/*
 		 * Truncate the previous file we overflowed into back to
 		 * the correct length, close it.
 		 */
 		if (fflush(overfile) !=3D 0)
 			err(1, "overflow");
 		if (ftruncate(fileno(overfile), truncofs) !=3D 0)
 			err(1, "overflow");
 		if (fclose(overfile) !=3D 0)
 			err(1, "overflow");
 		overfile =3D NULL;
 	}
 
 	if (n =3D=3D 0)
 		/* Just tidying up */
 		return;
 
 	lineno -=3D n;
 
 	/*
 	 * Wind the overflow file backwards to `n' lines before the
 	 * current one.
 	 */
 	do {
 		if (ftello(ofp) < (off_t)sizeof(buf))
 			rewind(ofp);
 		else
 			fseeko(ofp, -(off_t)sizeof(buf), SEEK_CUR);
 		if (ferror(ofp))
 			errx(1, "%s: can't seek", currfile);
 		if ((nread =3D fread(buf, 1, sizeof(buf), ofp)) =3D=3D 0)
 			errx(1, "can't read overflowed output");
 		if (fseeko(ofp, -(off_t)nread, SEEK_CUR) !=3D 0)
 			err(1, "%s", currfile);
 		for (i =3D 1; i <=3D nread; i++)
 			if (buf[nread - i] =3D=3D '\n' && n-- =3D=3D 0)
 				break;
 		if (ftello(ofp) =3D=3D 0)
 			break;
 	} while (n > 0);
 	if (fseeko(ofp, nread - i + 1, SEEK_CUR) !=3D 0)
 		err(1, "%s", currfile);
 
 	/*
 	 * getline() will read from here. Next call will truncate to
 	 * truncofs in this file.
 	 */
 	overfile =3D ofp;
 	truncofs =3D ftello(overfile);
 }
 
 /* Handle splits for /regexp/ and %regexp% patterns. */
 void
 do_rexp(const char *expr)
 {
 	regex_t cre;
 	intmax_t nwritten;
 	long ofs;
 	int first;
 	char *ecopy, *ep, *p, *pofs, *re;
 	FILE *ofp;
 
 	if ((ecopy =3D strdup(expr)) =3D=3D NULL)
 		err(1, "strdup");
 
 	re =3D ecopy + 1;
 	if ((pofs =3D strrchr(ecopy, *expr)) =3D=3D NULL || pofs[-1] =3D=3D '\\')
 		errx(1, "%s: missing trailing %c", expr, *expr);
 	*pofs++ =3D '\0';
 
 	if (*pofs !=3D '\0') {
 		errno =3D 0;
 		ofs =3D strtol(pofs, &ep, 10);
 		if (*ep !=3D '\0' || errno !=3D 0)
 			errx(1, "%s: bad offset", pofs);
 	} else
 		ofs =3D 0;
 
 	if (regcomp(&cre, re, REG_BASIC|REG_NOSUB) !=3D 0)
 		errx(1, "%s: bad regular expression", re);
 
 	if (*expr =3D=3D '/')
 		/* /regexp/: Save results to a file. */
 		ofp =3D newfile();
 	else {
 		/* %regexp%: Make a temporary file for overflow. */
 		if ((ofp =3D tmpfile()) =3D=3D NULL)
 			err(1, "tmpfile");
 	}
 
 	/* Read and output lines until we get a match. */
 	first =3D 1;
 	while ((p =3D getline()) !=3D NULL) {
 		if (fputs(p, ofp) !=3D 0)
 			break;
 		if (!first && regexec(&cre, p, 0, NULL, 0) =3D=3D 0)
 			break;
 		first =3D 0;
 	}
 
 	if (p =3D=3D NULL)
 		errx(1, "%s: no match", re);
 
 	if (ofs <=3D 0) {
 		/*
 		 * Negative (or zero) offset: throw back any lines we should
 		 * not have read yet.
 		  */
 		if (p !=3D NULL) {
 			toomuch(ofp, -ofs + 1);
 			nwritten =3D (intmax_t)truncofs;
 		} else
 			nwritten =3D (intmax_t)ftello(ofp);
 	} else {
 		/*
 		 * Positive offset: copy the requested number of lines
 		 * after the match.
 		 */
 		while (--ofs > 0 && (p =3D getline()) !=3D NULL)
 			fputs(p, ofp);
 		toomuch(NULL, 0);
 		nwritten =3D (intmax_t)ftello(ofp);
 		if (fclose(ofp) !=3D 0)
 			err(1, "%s", currfile);
 	}
 
 	if (!sflag && *expr =3D=3D '/')
 		printf("%jd\n", nwritten);
 
 	regfree(&cre);
 	free(ecopy);
 }
 
 /* Handle splits based on line number. */
 void
 do_lineno(const char *expr)
 {
 	long lastline, tgtline;
 	char *ep, *p;
 	FILE *ofp;
 
 	errno =3D 0;
 	tgtline =3D strtol(expr, &ep, 10);
 	if (tgtline <=3D 0 || errno !=3D 0 || *ep !=3D '\0')
 		errx(1, "%s: bad line number", expr);
 	lastline =3D tgtline;
 	if (lastline <=3D lineno)
 		errx(1, "%s: can't go backwards", expr);
 
 	while (nfiles < maxfiles - 1) {
 		ofp =3D newfile();
 		while (lineno + 1 !=3D lastline) {
 			if ((p =3D getline()) =3D=3D NULL)
 				errx(1, "%ld: out of range", lastline);
 			if (fputs(p, ofp) !=3D 0)
 				break;
 		}
 		if (!sflag)
 			printf("%jd\n", (intmax_t)ftello(ofp));
 		if (fclose(ofp) !=3D 0)
 			err(1, "%s", currfile);
 		if (reps-- =3D=3D 0)
 			break;
 		lastline +=3D tgtline;
 	}=20
 }
 
 --Multipart=_Mon__25_Sep_2006_04_03_27_+0300_L9jqCbwt3wbuiU4C--