summaryrefslogtreecommitdiff
path: root/usr/src/cmd/cut/cut.c
blob: e2a707aebc2fe12d4ca4ccda681fb4bd59b18fde (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */

/*
 * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

/*	Copyright (c) 1984, 1986, 1987, 1988, 1989 AT&T	*/
/*	  All Rights Reserved  	*/

#pragma ident	"%Z%%M%	%I%	%E% SMI"
#
/* cut : cut and paste columns of a table (projection of a relation) */
/* Release 1.5; handles single backspaces as produced by nroff    */

#include <stdio.h>	/* make: cc cut.c */
#include <ctype.h>
#include <limits.h>
#include <locale.h>
#include <wchar.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>

#define	MAX_RANGES	MAX_INPUT	/* maximum number of ranges */
					/* as input args */

static void	bfunc(void);
static void	bnfunc(void);
static void	cfunc(void);
static void	ffunc(void);
static wchar_t	*read_line(FILE *);
static void	process_list(char *);
static void	diag(const char *);
static void	usage(void);

static wchar_t wdel = '\t';
static int	dellen;
static int	supflag = 0;
static int	rstart[MAX_RANGES];
static int	rend[MAX_RANGES];
static int	nranges = 0;
static FILE	*inptr;
static char	dummy[MB_LEN_MAX];

static wchar_t	*linebuf = NULL;
static int	bufsiz;

int
main(int argc, char **argv)
{
	int	c;
	char	*list;
	int	status = 0;
	int	bflag, nflag, cflag, fflag, dflag, filenr;
	void	(*funcp)();

	bflag = nflag = cflag = fflag = dflag = 0;

	(void) setlocale(LC_ALL, "");

#if !defined(TEXT_DOMAIN)		/* Should be defined by cc -D */
#define	TEXT_DOMAIN	"SYS_TEST"	/* Use this only if it weren't. */
#endif
	(void) textdomain(TEXT_DOMAIN);

	while ((c = getopt(argc, argv, "b:c:d:f:ns")) != EOF)
		switch (c) {
			case 'b':
				if (fflag || cflag)
					usage();
				bflag++;
				list = optarg;
				break;

			case 'c':
				if (fflag || bflag)
					usage();
				cflag++;
				list = optarg;
				break;

			case 'd':
				dellen = mbtowc(&wdel, optarg, MB_CUR_MAX);
				if (dellen == -1) {
					diag("no delimiter specified");
				} else if (dellen != strlen(optarg))
					diag("invalid delimiter");
				dflag++;
				break;

			case 'f':
				if (bflag || cflag)
					usage();
				fflag++;
				list = optarg;
				break;

			case 'n':
				nflag++;
				break;

			case 's':
				supflag++;
				break;

			case '?':
				usage();
		}

	argv = &argv[optind];
	argc -= optind;

	/* you must use one and only one option -b, -c, or -f */
	if (!(cflag || fflag || bflag))
		usage();

	/*
	 * Make sure combination of options is correct
	 */
	if (nflag) {
		if (cflag || fflag) {
			(void) fprintf(stderr, gettext(
			    "cut: -n may only be used with -b\n"));
			usage();
		}
	}

	if (dflag || supflag) {
		if (bflag || cflag) {
			if (dflag)
				(void) fprintf(stderr, gettext(
				    "cut: -d may only be used with -f\n"));
			if (supflag)
				(void) fprintf(stderr, gettext(
				    "cut: -s may only be used with -f\n"));
			usage();
		}
	}

	process_list(list);

	if (cflag) {
		funcp = cfunc;
	} else if (bflag) {
		if (nflag)
			funcp = bnfunc;
		else
			funcp = bfunc;
	} else { /* fflag */
		funcp = ffunc;
	}

	if (nranges == 0)
		diag("no list specified");

	filenr = 0;
	do {	/* for all input files */
		if (argc == 0 || strcmp(argv[filenr], "-") == 0)
			inptr = stdin;
		else
			if ((inptr = fopen(argv[filenr], "r")) == NULL) {
				(void) fprintf(stderr, "cut: %s: %s\n",
				    argv[filenr], strerror(errno));
				status = 1;
				continue;
			}
		(*funcp)();
		(void) fclose(inptr);
	} while (++filenr < argc);
	return (status);
}

/* parse range list argument and set-up rstart/rend array */
void
process_list(char *list)
{
	int inrange = 0;
	int start = 0;
	int num = 0;
	char *rlist = list;
	char *p;
	int i, j;
	int tmp;

	/* first, parse list of ranges */
	do {
		p = rlist;
		switch (*p) {
			case '-':
				if (inrange)
					diag("invalid range specifier");

				inrange = 1;
				if (num == 0)
					start = 1;
				else {
					start = num;
					num = 0;
				}
				break;

			case '\0':
			case ',':
			case ' ':
			case '\t':
				/*
				 * this is temporary - it will change
				 * when the isblank() routine becomes
				 * available.
				 */
				if (nranges == MAX_RANGES)
					diag("too many ranges specified");

				if (inrange) {
					if (num == 0)
						num = INT_MAX;
					if (num < start)
						diag("ranges must be "
						    "increasing");
					rstart[nranges] = start;
					rend[nranges] = num;
					nranges++;
				} else {
					rstart[nranges] = num;
					rend[nranges] = num;
					nranges++;
				}

				num = 0;
				start = 0;
				inrange = 0;

				if (*p == '\0')
					continue;
				break;

			default:
				if (!isdigit(*p))
					diag("invalid character in range");
				num = atoi(p);
				while (isdigit(*rlist))
					rlist++;
				continue;
		}
		rlist++;
	} while (*p != '\0');

	/* then, consolidate ranges where possible */
	for (i = 0; i < (nranges - 1); i++) {
		for (j = i + 1; j < nranges; j++) {
			if (rstart[i] != 0 && rend[i] != 0 &&
			    (!(rend[i] < rstart[j] || rstart[i] > rend[j]))) {
				if (rstart[i] < rstart[j])
					rstart[j] = rstart[i];
				if (rend[i] > rend[j])
					rend[j] = rend[i];
				rstart[i] = 0;
				rend[i] = 0;
				break;
			}
		}
	}

	/* then, weed out the zero'ed/consolidated entries */
	for (i = 0; i < nranges; ) {
		if (rstart[i] == 0 && rend[i] == 0) {
			for (j = i; j < (nranges - 1); j++) {
				rstart[j] = rstart[j+1];
				rend[j] = rend[j+1];
			}
			nranges--;
		} else if (rstart[i] == 0 || rend[i] == 0) {
			diag("Internal error processing input");
		} else {
			i++;
		}
	}

	/* finally, sort the remaining entries */
	for (i = 0; i < (nranges - 1); i++) {
		for (j = i+1; j < nranges; j++) {
			if (rstart[i] > rend[j]) {
				tmp = rstart[i];
				rstart[i] = rstart[j];
				rstart[j] = tmp;

				tmp = rend[i];
				rend[i] = rend[j];
				rend[j] = tmp;
			}
		}
	}

#ifdef DEBUG
	/* dump ranges */
	for (i = 0; i < nranges; i++) {
		(void) printf("Range %d - start: %d end: %d\n", i, rstart[i],
		    rend[i]);
	}
#endif
}

/* called when -c is used */
/* print out those characters selected */

void
cfunc(void)
{
	wint_t	c;		/* current character */
	int	pos = 0;	/* current position within line */
	int	inrange = 0;	/* is 'pos' within a range */
	int	rndx = 0;	/* current index into range table */

	while ((c = fgetwc(inptr)) != EOF) {
		if (c == '\n') {
			(void) putchar('\n');

			/* reset per-line variables */
			pos = 0;
			inrange = 0;
			rndx = 0;
		} else {
			pos++;

			/*
			 * check if current character is within range and,
			 * if so, print it.
			 */
			if (!inrange)
				if (pos == rstart[rndx])
					inrange = 1;

			if (inrange) {
				(void) putwchar(c);
				if (pos == rend[rndx]) {
					inrange = 0;
					rndx++;
					/*
					 * optimization -
					 * check for last range index
					 * and eat chars until newline
					 * if so.
					 */
				}
			}
		}
	}
}

void
bfunc(void) /* called when -b is used but -n is not */
{
	int	c;		/* current character */
	int	pos = 0;	/* current position within line */
	int	inrange = 0;	/* is 'pos' within a range */
	int	rndx = 0;	/* current index into range table */

	while ((c = getc(inptr)) != EOF) {
		if (c == L'\n') {
			(void) putchar('\n');

			/* reset per-line variables */
			pos = 0;
			inrange = 0;
			rndx = 0;
		} else {
			pos++;

			/*
			 * check if current character is within range and,
			 * if so, print it.
			 */
			if (!inrange)
				if (pos == rstart[rndx])
					inrange = 1;

			if (inrange) {
				(void) putchar(c);
				if (pos == rend[rndx]) {
					inrange = 0;
					rndx++;
					/*
					 * optimization -
					 * check for last range index
					 * and eat chars until newline
					 * if so.
					 */
				}
			}
		}
	}
}


void
bnfunc(void) /* called when -b -n is used */
{
	wint_t	c;		/* current character */
	int	pos = 0;	/* current position within line */
	int	inrange = 0;	/* is 'pos' within a range */
	int	rndx = 0;	/* current index into range table */
	int	wlen;		/* byte length of current wide char */

	while ((c = fgetwc(inptr)) != EOF) {
		if (c == '\n') {
			(void) putchar('\n');

			/* reset per-line variables */
			pos = 0;
			inrange = 0;
			rndx = 0;
		} else {
			if (rndx >= nranges)
				continue;

			if ((wlen = wctomb(dummy, c)) < 0)
				diag("invalid multibyte character");
			pos += wlen;

			/*
			 * when trying to figure this out, remember that
			 * pos is actually pointing to the start byte of
			 * the next char.
			 */

			/*
			 * if char starts after beginning of range,
			 * for the moment, consider it in range.
			 */
			if (!inrange && pos < rstart[rndx])
				continue;

			/*
			 * If tail of the multibyte is out of the range.
			 * do not print the character.
			 * (See XCU4)
			 */
			if (pos <= rend[rndx]) {
				inrange = 1;
				(void) putwchar(c);
				continue;
			}
			inrange = 0;
			while (++rndx < nranges && pos >= rstart[rndx]) {
				if (pos <= rend[rndx]) {
					inrange = 1;
					(void) putwchar(c);
					break;
				}
			}
		}
	}
}

wchar_t *
read_line(FILE *fp)
{
	wint_t	c;
	wchar_t	*cp;
	int charcnt;

	/* alloc the line buffer if it isn't already there */
	if (linebuf == NULL) {
		bufsiz = BUFSIZ - 1;
		if ((linebuf = (wchar_t *)malloc((bufsiz + 1) *
		    sizeof (wchar_t))) == NULL)
			diag("unable to allocate enough memory");
	}

	cp = linebuf;
	charcnt = 0;
	while ((c = fgetwc(fp)) != EOF) {
		if (c == '\n') {
			*cp = NULL;
			return (linebuf);
		} else {
			charcnt++;
			if (charcnt == bufsiz) {
				/*
				 * there is no line length limitation so we
				 * have to be ready to expand the line buffer.
				 */
				bufsiz += BUFSIZ;
				if ((linebuf = (wchar_t *)realloc(linebuf,
				    (bufsiz + 1) * sizeof (wchar_t))) == NULL)
					diag("unable to allocate "
					    "enough memory");

				cp = linebuf + charcnt - 1;
			}
			*cp++ = c;
		}
	}

	if (cp != linebuf) {
		*cp = NULL;
		return (linebuf);
	} else
		return (NULL);
}

void
ffunc(void)  /* called when -f is used */
{
	int	fpos;		/* current field position within line */
	int	inrange;	/* is 'pos' within a range */
	int	rndx;		/* current index into range table */
	int	need_del;	/* need to put a delimiter char in output */
	wchar_t	*linep;		/* pointer to line buffer */
	wchar_t	*cp, *ncp;	/* working pointers into linebuf */

	while ((linep = read_line(inptr)) != NULL) {

		/* first, prune out line with no delimiters */
		if (wcschr(linep, wdel) == NULL) {
#if !defined(__lint)	/* lint doesn't grok "%ws" */
			if (!supflag)
				(void) printf("%ws\n", linep);
#endif
			continue;
		}

		/* init per-line variable */
		fpos = 1;
		inrange = 0;
		rndx = 0;
		need_del = 0;

		for (ncp = cp = linep; ncp != NULL; fpos++) {
			/* why continue processing if no more ranges? */
			if (rndx >= nranges)
				break;

			/* find the next field delimiter */
			ncp = wcschr(cp, wdel);

			if (!inrange)
				if (fpos == rstart[rndx])
					inrange = 1;

			if (inrange) {
				if (need_del)
					(void) putwchar(wdel);

				if (ncp == NULL) {
					/*
					 * if there are no more delimiters
					 * and we are in the range, print
					 * out the rest of the line.
					 */
#if !defined(__lint)	/* lint doesn't grok "%ws" */
					(void) printf("%ws", cp);
#endif
					break;
				}
				else
					while (cp != ncp)
						(void) putwchar(*cp++);
				need_del = 1;

				if (fpos == rend[rndx]) {
					inrange = 0;
					rndx++;
				}
			}

			if (ncp != NULL)
				cp = ncp + 1;
		}
		(void) putchar('\n');
	}
}


void
diag(const char *s)
{
	(void) fprintf(stderr, "cut: ");
	(void) fprintf(stderr, gettext(s));
	(void) fprintf(stderr, "\n");
	exit(2);
}


void
usage(void)
{
	(void) fprintf(stderr, gettext(
	    "usage: cut -b list [-n] [filename ...]\n"
	    "       cut -c list [filename ...]\n"
	    "       cut -f list [-d delim] [-s] [filename]\n"));
	exit(2);
}