Home | History | Annotate | Line # | Download | only in sort
sort.c revision 1.8
      1 /*	$NetBSD: sort.c,v 1.8 2000/10/16 21:48:15 jdolecek 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.8 2000/10/16 21:48:15 jdolecek 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 const char *tmpdir = _PATH_TMP;
     85 
     86 static void cleanup __P((void));
     87 static void onsignal __P((int));
     88 static void usage __P((const char *));
     89 
     90 int main __P((int argc, char **argv));
     91 
     92 int
     93 main(argc, argv)
     94 	int argc;
     95 	char *argv[];
     96 {
     97 	extern int optind;
     98 	extern char *optarg;
     99 	int (*get) __P((int, union f_handle, int, struct recheader *, u_char *,
    100 	    struct field *));
    101 	int ch, i, stdinflag = 0, tmp = 0;
    102 	char cflag = 0, mflag = 0;
    103 	char *outfile, *outpath = 0;
    104 	struct field fldtab[ND+2], *ftpos;
    105 	union f_handle filelist;
    106 	FILE *outfp = NULL;
    107 	memset(fldtab, 0, (ND+2)*sizeof(struct field));
    108 	memset(d_mask, 0, NBINS);
    109 	d_mask[REC_D = '\n'] = REC_D_F;
    110 	SINGL_FLD = SEP_FLAG = 0;
    111 	d_mask['\t'] = d_mask[' '] = BLANK | FLD_D;
    112 	ftpos = fldtab;
    113 	fixit(&argc, argv);
    114 	while ((ch = getopt(argc, argv, "bcdfik:mHno:rt:T:ux")) != EOF) {
    115 	if ((outfile = getenv("TMPDIR")))
    116 		tmpdir = outfile;
    117 	switch (ch) {
    118 		case 'b': fldtab->flags |= BI | BT;
    119 			break;
    120 		case 'd':
    121 		case 'i':
    122 		case 'f':
    123 		case 'n':
    124 		case 'r': tmp |= optval(ch, 0);
    125 			if (tmp & R && tmp & F)
    126 				fldtab->weights = RFtable;
    127 			else if (tmp & F)
    128 				fldtab->weights = Ftable;
    129 			else if(tmp & R)
    130 				fldtab->weights = Rascii;
    131 			fldtab->flags |= tmp;
    132 			break;
    133 		case 'o':
    134 			outpath = optarg;
    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|N) || 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 		fldreset(fldtab);
    203 		fldtab[0].flags &= ~F;
    204 	}
    205 	settables(fldtab[0].flags);
    206 	num_init();
    207 	fldtab->weights = gweights;
    208 	if (optind == argc) {
    209 		static char *names[2];
    210 
    211 		names[0] = devstdin;
    212 		names[1] = NULL;
    213 		filelist.names = names;
    214 		optind--;
    215 	} else
    216 		filelist.names = argv+optind;
    217 	if (SINGL_FLD)
    218 		get = makeline;
    219 	else
    220 		get = makekey;
    221 	if (cflag) {
    222 		order(filelist, get, fldtab);
    223 		/* NOT REACHED */
    224 	}
    225 	if (!outpath) {
    226 		(void)snprintf(toutpath,
    227 		    sizeof(toutpath), "%sstdout", _PATH_DEV);
    228 		outfile = outpath = toutpath;
    229 	} else if (!(ch = access(outpath, 0)) &&
    230 	    strncmp(_PATH_DEV, outpath, 5)) {
    231 		struct sigaction act = {0};
    232 		int sigtable[] = {SIGHUP, SIGINT, SIGPIPE, SIGXCPU, SIGXFSZ,
    233 		    SIGVTALRM, SIGPROF, 0};
    234 		int outfd;
    235 		errno = 0;
    236 		if (access(outpath, W_OK))
    237 			err(2, "%s", outpath);
    238 		act.sa_handler = onsignal;
    239 		act.sa_flags = SA_RESTART | SA_RESETHAND;
    240 		(void)snprintf(toutpath, sizeof(toutpath), "%sXXXX", outpath);
    241 		if ((outfd = mkstemp(toutpath)) < 0 ||
    242 		    (outfp = fdopen(outfd, "w")) == 0)
    243 			err(2, "temporary file %s", toutpath);
    244 		outfile = toutpath;
    245 		(void)atexit(cleanup);
    246 		for (i = 0; sigtable[i]; ++i)	/* always unlink toutpath */
    247 			sigaction(sigtable[i], &act, 0);
    248 	} else
    249 		outfile = outpath;
    250 	if (outfp == NULL && (outfp = fopen(outfile, "w")) == NULL)
    251 		err(2, "output file %s", outfile);
    252 	if (mflag)
    253 		fmerge(-1, filelist, argc-optind, get, outfp, putline, fldtab);
    254 	else
    255 		fsort(-1, 0, filelist, argc-optind, outfp, fldtab);
    256 	if (outfile != outpath) {
    257 		if (access(outfile, 0))
    258 			err(2, "%s", outfile);
    259 		(void)unlink(outpath);
    260 		if (link(outfile, outpath))
    261 			err(2, "cannot link %s: output left in %s",
    262 			    outpath, outfile);
    263 		(void)unlink(outfile);
    264 	}
    265 	exit(0);
    266 }
    267 
    268 static void
    269 onsignal(sig)
    270 	int sig;
    271 {
    272 	cleanup();
    273 }
    274 
    275 static void
    276 cleanup()
    277 {
    278 	if (toutpath[0])
    279 		(void)unlink(toutpath);
    280 }
    281 
    282 static void
    283 usage(msg)
    284 	const char *msg;
    285 {
    286 	if (msg)
    287 		(void)fprintf(stderr, "sort: %s\n", msg);
    288 	(void)fprintf(stderr, "usage: [-o output] [-cmubdfinr] [-t char] ");
    289 	(void)fprintf(stderr, "[-T char] [-k keydef] ... [files]\n");
    290 	exit(2);
    291 }
    292