Home | History | Annotate | Line # | Download | only in sort
sort.c revision 1.13
      1 /*	$NetBSD: sort.c,v 1.13 2001/01/11 14:05:24 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.13 2001/01/11 14:05:24 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 #include <locale.h>
     64 
     65 int REC_D = '\n';
     66 u_char d_mask[NBINS];		/* flags for rec_d, field_d, <blank> */
     67 /*
     68  * weight tables.  Gweights is one of ascii, Rascii..
     69  * modified to weight rec_d = 0 (or 255)
     70  */
     71 extern u_char gweights[NBINS];
     72 u_char ascii[NBINS], Rascii[NBINS], RFtable[NBINS], Ftable[NBINS];
     73 /*
     74  * masks of ignored characters.  Alltable is 256 ones
     75  */
     76 u_char dtable[NBINS], itable[NBINS], alltable[NBINS];
     77 int SINGL_FLD = 0, SEP_FLAG = 0, UNIQUE = 0;
     78 struct coldesc clist[(ND+1)*2];
     79 int ncols = 0;
     80 extern struct coldesc clist[(ND+1)*2];
     81 extern int ncols;
     82 
     83 /*
     84  * Default to stable sort.
     85  */
     86 int stable_sort = 1;
     87 
     88 char toutpath[_POSIX_PATH_MAX];
     89 
     90 static void cleanup __P((void));
     91 static void onsignal __P((int));
     92 static void usage __P((const char *));
     93 
     94 int main __P((int argc, char **argv));
     95 
     96 int
     97 main(argc, argv)
     98 	int argc;
     99 	char *argv[];
    100 {
    101 	get_func_t get;
    102 	int ch, i, stdinflag = 0, tmp = 0;
    103 	char cflag = 0, mflag = 0;
    104 	char *outfile, *outpath = 0;
    105 	struct field fldtab[ND+2], *ftpos;
    106 	struct filelist filelist;
    107 	FILE *outfp = NULL;
    108 
    109 	setlocale(LC_ALL, "");
    110 
    111 	memset(fldtab, 0, (ND+2)*sizeof(struct field));
    112 	memset(d_mask, 0, NBINS);
    113 	d_mask[REC_D = '\n'] = REC_D_F;
    114 	SINGL_FLD = SEP_FLAG = 0;
    115 	d_mask['\t'] = d_mask[' '] = BLANK | FLD_D;
    116 	ftpos = fldtab;
    117 
    118 	fixit(&argc, argv);
    119 
    120 	while ((ch = getopt(argc, argv, "bcdfik:mHno:rsSt:T:ux")) != -1) {
    121 		switch (ch) {
    122 		case 'b':
    123 			fldtab->flags |= BI | BT;
    124 			break;
    125 		case 'c':
    126 			cflag = 1;
    127 			break;
    128 		case 'd': case 'f': case 'i': case 'n': case 'r':
    129 			tmp |= optval(ch, 0);
    130 			if (tmp & R && tmp & F)
    131 				fldtab->weights = RFtable;
    132 			else if (tmp & F)
    133 				fldtab->weights = Ftable;
    134 			else if(tmp & R)
    135 				fldtab->weights = Rascii;
    136 			fldtab->flags |= tmp;
    137 			break;
    138 		case 'H':
    139 			PANIC = 0;
    140 			break;
    141 		case 'k':
    142 			setfield(optarg, ++ftpos, fldtab->flags);
    143 			break;
    144 		case 'm':
    145 			mflag = 1;
    146 			break;
    147 		case 'o':
    148 			outpath = optarg;
    149 			break;
    150 		case 's':
    151 			/* for GNU sort compatibility (this is our default) */
    152 			stable_sort = 1;
    153 			break;
    154 		case 'S':
    155 			stable_sort = 0;
    156 			break;
    157 		case 't':
    158 			if (SEP_FLAG)
    159 				usage("multiple field delimiters");
    160 			SEP_FLAG = 1;
    161 			d_mask[' '] &= ~FLD_D;
    162 			d_mask['\t'] &= ~FLD_D;
    163 			d_mask[(u_char)*optarg] |= FLD_D;
    164 			if (d_mask[(u_char)*optarg] & REC_D_F)
    165 				err(2, "record/field delimiter clash");
    166 			break;
    167 		case 'T':
    168 			if (REC_D != '\n')
    169 				usage("multiple record delimiters");
    170 			if ('\n' == (REC_D = *optarg))
    171 				break;
    172 			d_mask['\n'] = d_mask[' '];
    173 			d_mask[REC_D] = REC_D_F;
    174 			break;
    175 		case 'u':
    176 			UNIQUE = 1;
    177 			break;
    178 		case '?':
    179 		default:
    180 			usage("");
    181 		}
    182 	}
    183 	if (cflag && argc > optind+1)
    184 		errx(2, "too many input files for -c option");
    185 	if (argc - 2 > optind && !strcmp(argv[argc-2], "-o")) {
    186 		outpath = argv[argc-1];
    187 		argc -= 2;
    188 	}
    189 	if (mflag && argc - optind > (MAXFCT - (16+1))*16)
    190 		errx(2, "too many input files for -m option");
    191 	for (i = optind; i < argc; i++) {
    192 		/* allow one occurrence of /dev/stdin */
    193 		if (!strcmp(argv[i], "-") || !strcmp(argv[i], _PATH_STDIN)) {
    194 			if (stdinflag)
    195 				warnx("ignoring extra \"%s\" in file list",
    196 				    argv[i]);
    197 			else
    198 				stdinflag = 1;
    199 		} else if ((ch = access(argv[i], R_OK)))
    200 			err(2, "%s", argv[i]);
    201 	}
    202 	if (!(fldtab->flags & (I|D|N) || fldtab[1].icol.num)) {
    203 		SINGL_FLD = 1;
    204 		fldtab[0].icol.num = 1;
    205 	} else {
    206 		if (!fldtab[1].icol.num) {
    207 			fldtab[0].flags &= ~(BI|BT);
    208 			setfield("1", ++ftpos, fldtab->flags);
    209 		}
    210 		fldreset(fldtab);
    211 		fldtab[0].flags &= ~F;
    212 	}
    213 	settables(fldtab[0].flags);
    214 	num_init();
    215 	fldtab->weights = gweights;
    216 	if (optind == argc) {
    217 		static const char * const names[] = { _PATH_STDIN, NULL };
    218 
    219 		filelist.names = names;
    220 		optind--;
    221 	} else
    222 		filelist.names = (const char * const *) &argv[optind];
    223 	if (SINGL_FLD)
    224 		get = makeline;
    225 	else
    226 		get = makekey;
    227 	if (cflag) {
    228 		order(&filelist, get, fldtab);
    229 		/* NOT REACHED */
    230 	}
    231 	if (!outpath) {
    232 		(void)snprintf(toutpath,
    233 		    sizeof(toutpath), "%sstdout", _PATH_DEV);
    234 		outfile = outpath = toutpath;
    235 	} else if (!(ch = access(outpath, 0)) &&
    236 	    strncmp(_PATH_DEV, outpath, 5)) {
    237 		struct sigaction act = {0};
    238 		int sigtable[] = {SIGHUP, SIGINT, SIGPIPE, SIGXCPU, SIGXFSZ,
    239 		    SIGVTALRM, SIGPROF, 0};
    240 		int outfd;
    241 		errno = 0;
    242 		if (access(outpath, W_OK))
    243 			err(2, "%s", outpath);
    244 		act.sa_handler = onsignal;
    245 		act.sa_flags = SA_RESTART | SA_RESETHAND;
    246 		(void)snprintf(toutpath, sizeof(toutpath), "%sXXXX", outpath);
    247 		if ((outfd = mkstemp(toutpath)) < 0 ||
    248 		    (outfp = fdopen(outfd, "w")) == 0)
    249 			err(2, "temporary file %s", toutpath);
    250 		outfile = toutpath;
    251 		(void)atexit(cleanup);
    252 		for (i = 0; sigtable[i]; ++i)	/* always unlink toutpath */
    253 			sigaction(sigtable[i], &act, 0);
    254 	} else
    255 		outfile = outpath;
    256 
    257 	if (outfp == NULL && (outfp = fopen(outfile, "w")) == NULL)
    258 		err(2, "output file %s", outfile);
    259 
    260 	if (mflag) {
    261 		fmerge(-1, 0, &filelist, argc-optind, get, outfp, putline,
    262 			fldtab);
    263 	} else
    264 		fsort(-1, 0, 0, &filelist, argc-optind, outfp, fldtab);
    265 
    266 	if (outfile != outpath) {
    267 		if (access(outfile, 0))
    268 			err(2, "%s", outfile);
    269 		(void)unlink(outpath);
    270 		if (link(outfile, outpath))
    271 			err(2, "cannot link %s: output left in %s",
    272 			    outpath, outfile);
    273 		(void)unlink(outfile);
    274 	}
    275 	exit(0);
    276 }
    277 
    278 static void
    279 onsignal(sig)
    280 	int sig;
    281 {
    282 	cleanup();
    283 }
    284 
    285 static void
    286 cleanup()
    287 {
    288 	if (toutpath[0])
    289 		(void)unlink(toutpath);
    290 }
    291 
    292 static void
    293 usage(msg)
    294 	const char *msg;
    295 {
    296 	if (msg)
    297 		(void)fprintf(stderr, "sort: %s\n", msg);
    298 	(void)fprintf(stderr, "usage: [-o output] [-cmubdfinr] [-t char] ");
    299 	(void)fprintf(stderr, "[-T char] [-k keydef] ... [files]\n");
    300 	exit(2);
    301 }
    302