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