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