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