Home | History | Annotate | Line # | Download | only in sort
sort.c revision 1.2
      1 /*	$NetBSD: sort.c,v 1.2 2000/10/07 18:37:10 bjh21 Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1993
      5  *	The Regents of the University of California.  All rights reserved.
      6  *
      7  * This code is derived from software contributed to Berkeley by
      8  * Peter McIlroy.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  * 3. All advertising materials mentioning features or use of this software
     19  *    must display the following acknowledgement:
     20  *	This product includes software developed by the University of
     21  *	California, Berkeley and its contributors.
     22  * 4. Neither the name of the University nor the names of its contributors
     23  *    may be used to endorse or promote products derived from this software
     24  *    without specific prior written permission.
     25  *
     26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     36  * SUCH DAMAGE.
     37  */
     38 
     39 /* Sort sorts a file using an optional user-defined key.
     40  * Sort uses radix sort for internal sorting, and allows
     41  * a choice of merge sort and radix sort for external sorting.
     42  */
     43 
     44 #include "sort.h"
     45 #include "fsort.h"
     46 #include "pathnames.h"
     47 
     48 #ifndef lint
     49 __COPYRIGHT("@(#) Copyright (c) 1993\n\
     50 	The Regents of the University of California.  All rights reserved.\n");
     51 #endif /* not lint */
     52 
     53 #ifndef lint
     54 __RCSID("$NetBSD: sort.c,v 1.2 2000/10/07 18:37:10 bjh21 Exp $");
     55 __SCCSID("@(#)sort.c	8.1 (Berkeley) 6/6/93");
     56 #endif /* not lint */
     57 
     58 #include <paths.h>
     59 #include <signal.h>
     60 #include <stdlib.h>
     61 #include <string.h>
     62 #include <unistd.h>
     63 
     64 int REC_D = '\n';
     65 u_char d_mask[NBINS];		/* flags for rec_d, field_d, <blank> */
     66 /*
     67  * weight tables.  Gweights is one of ascii, Rascii..
     68  * modified to weight rec_d = 0 (or 255)
     69  */
     70 extern u_char gweights[NBINS];
     71 u_char ascii[NBINS], Rascii[NBINS], RFtable[NBINS], Ftable[NBINS];
     72 /*
     73  * masks of ignored characters.  Alltable is 256 ones
     74  */
     75 u_char dtable[NBINS], itable[NBINS], alltable[NBINS];
     76 int SINGL_FLD = 0, SEP_FLAG = 0, UNIQUE = 0;
     77 struct coldesc clist[(ND+1)*2];
     78 int ncols = 0;
     79 extern struct coldesc clist[(ND+1)*2];
     80 extern int ncols;
     81 
     82 char devstdin[] = _PATH_STDIN;
     83 char toutpath[_POSIX_PATH_MAX];
     84 
     85 static void cleanup __P((void));
     86 static void onsignal __P((int));
     87 static void usage __P((char *));
     88 
     89 int main __P((int argc, char **argv));
     90 
     91 int
     92 main(argc, argv)
     93 	int argc;
     94 	char *argv[];
     95 {
     96 	extern int optind;
     97 	extern char *optarg;
     98 	int (*get) __P((int, union f_handle, int, struct recheader *, u_char *,
     99 	    struct field *));
    100 	int ch, i, stdinflag = 0, tmp = 0;
    101 	char cflag = 0, mflag = 0, nflag = 0;
    102 	char *outfile, *outpath = 0;
    103 	struct field fldtab[ND+2], *ftpos;
    104 	union f_handle filelist;
    105 	FILE *outfd;
    106 	memset(fldtab, 0, (ND+2)*sizeof(struct field));
    107 	memset(d_mask, 0, NBINS);
    108 	d_mask[REC_D = '\n'] = REC_D_F;
    109 	SINGL_FLD = SEP_FLAG = 0;
    110 	d_mask['\t'] = d_mask[' '] = BLANK | FLD_D;
    111 	ftpos = fldtab;
    112 	fixit(&argc, argv);
    113 	while ((ch = getopt(argc, argv, "bcdfik:mHno:rt:T:ux")) != EOF) {
    114 	switch (ch) {
    115 		case 'b': fldtab->flags |= BI | BT;
    116 			break;
    117 		case 'd':
    118 		case 'i':
    119 		case 'f':
    120 		case 'r': tmp |= optval(ch, 0);
    121 			if (tmp & R && tmp & F)
    122 				fldtab->weights = RFtable;
    123 			else if (tmp & F)
    124 				fldtab->weights = Ftable;
    125 			else if(tmp & R)
    126 				fldtab->weights = Rascii;
    127 			fldtab->flags |= tmp;
    128 			break;
    129 		case 'o':
    130 			outpath = optarg;
    131 			break;
    132 		case 'n':
    133 			nflag = 1;
    134 			setfield("1n", ++ftpos, fldtab->flags&(~R));
    135 			break;
    136 		case 'k':
    137 			 setfield(optarg, ++ftpos, fldtab->flags);
    138 			break;
    139 		case 't':
    140 			if (SEP_FLAG)
    141 				usage("multiple field delimiters");
    142 			SEP_FLAG = 1;
    143 			d_mask[' '] &= ~FLD_D;
    144 			d_mask['\t'] &= ~FLD_D;
    145 			d_mask[(u_char)*optarg] |= FLD_D;
    146 			if (d_mask[(u_char)*optarg] & REC_D_F)
    147 				err(2, "record/field delimiter clash");
    148 			break;
    149 		case 'T':
    150 			if (REC_D != '\n')
    151 				usage("multiple record delimiters");
    152 			if ('\n' == (REC_D = *optarg))
    153 				break;
    154 			d_mask['\n'] = d_mask[' '];
    155 			d_mask[REC_D] = REC_D_F;
    156 			break;
    157 		case 'u':
    158 			UNIQUE = 1;
    159 			break;
    160 		case 'c':
    161 			cflag = 1;
    162 			break;
    163 		case 'm':
    164 			mflag = 1;
    165 			break;
    166 		case 'H':
    167 			PANIC = 0;
    168 			break;
    169 		case '?':
    170 		default: usage("");
    171 		}
    172 	}
    173 	if (cflag && argc > optind+1)
    174 		errx(2, "too many input files for -c option");
    175 	if (argc - 2 > optind && !strcmp(argv[argc-2], "-o")) {
    176 		outpath = argv[argc-1];
    177 		argc -= 2;
    178 	}
    179 	if (mflag && argc - optind > (MAXFCT - (16+1))*16)
    180 		errx(2, "too many input files for -m option");
    181 	for (i = optind; i < argc; i++) {
    182 		/* allow one occurrence of /dev/stdin */
    183 		if (!strcmp(argv[i], "-") || !strcmp(argv[i], devstdin)) {
    184 			if (stdinflag)
    185 				warnx("ignoring extra \"%s\" in file list",
    186 				    argv[i]);
    187 			else {
    188 				stdinflag = 1;
    189 				argv[i] = devstdin;
    190 			}
    191 		} else if ((ch = access(argv[i], R_OK)))
    192 			err(2, "%s", argv[i]);
    193 	}
    194 	if (!(fldtab->flags & (I|D) || fldtab[1].icol.num)) {
    195 		SINGL_FLD = 1;
    196 		fldtab[0].icol.num = 1;
    197 	} else {
    198 		if (!fldtab[1].icol.num) {
    199 			fldtab[0].flags &= ~(BI|BT);
    200 			setfield("1", ++ftpos, fldtab->flags);
    201 		}
    202 		if (nflag)
    203 			fldtab[1].flags |= fldtab->flags;
    204 		fldreset(fldtab);
    205 		fldtab[0].flags &= ~F;
    206 	}
    207 	settables(fldtab[0].flags);
    208 	num_init();
    209 	fldtab->weights = gweights;
    210 	if (optind == argc)
    211 		argv[--optind] = devstdin;
    212 	filelist.names = argv+optind;
    213 	if (SINGL_FLD)
    214 		get = makeline;
    215 	else
    216 		get = makekey;
    217 	if (cflag) {
    218 		order(filelist, get, fldtab);
    219 		/* NOT REACHED */
    220 	}
    221 	if (!outpath) {
    222 		(void)snprintf(toutpath,
    223 		    sizeof(toutpath), "%sstdout", _PATH_DEV);
    224 		outfile = outpath = toutpath;
    225 	} else if (!(ch = access(outpath, 0)) &&
    226 	    strncmp(_PATH_DEV, outpath, 5)) {
    227 		struct sigaction act = {0};
    228 		int sigtable[] = {SIGHUP, SIGINT, SIGPIPE, SIGXCPU, SIGXFSZ,
    229 		    SIGVTALRM, SIGPROF, 0};
    230 		errno = 0;
    231 		if (access(outpath, W_OK))
    232 			err(2, "%s", outpath);
    233 		act.sa_handler = onsignal;
    234 		act.sa_flags = SA_RESTART | SA_RESETHAND;
    235 		(void)snprintf(toutpath, sizeof(toutpath), "%sXXXX", outpath);
    236 		outfile = mktemp(toutpath);
    237 		if (!outfile)
    238 			err(2, "%s", toutpath);
    239 		(void)atexit(cleanup);
    240 		for (i = 0; sigtable[i]; ++i)	/* always unlink toutpath */
    241 			sigaction(sigtable[i], &act, 0);
    242 	} else outfile = outpath;
    243 	if (!(outfd = fopen(outfile, "w")))
    244 		err(2, "%s", outfile);
    245 	if (mflag)
    246 		fmerge(-1, filelist, argc-optind, get, outfd, putline, fldtab);
    247 	else
    248 		fsort(-1, 0, filelist, argc-optind, outfd, fldtab);
    249 	if (outfile != outpath) {
    250 		if (access(outfile, 0))
    251 			err(2, "%s", outfile);
    252 		(void)unlink(outpath);
    253 		if (link(outfile, outpath))
    254 			err(2, "cannot link %s: output left in %s",
    255 			    outpath, outfile);
    256 		(void)unlink(outfile);
    257 	}
    258 	exit(0);
    259 }
    260 
    261 static void
    262 onsignal(sig)
    263 	int sig;
    264 {
    265 	cleanup();
    266 }
    267 
    268 static void
    269 cleanup()
    270 {
    271 	if (toutpath[0])
    272 		(void)unlink(toutpath);
    273 }
    274 
    275 static void
    276 usage(msg)
    277 	char *msg;
    278 {
    279 	if (msg)
    280 		(void)fprintf(stderr, "sort: %s\n", msg);
    281 	(void)fprintf(stderr, "usage: [-o output] [-cmubdfinr] [-t char] ");
    282 	(void)fprintf(stderr, "[-T char] [-k keydef] ... [files]\n");
    283 	exit(2);
    284 }
    285