Home | History | Annotate | Line # | Download | only in column
column.c revision 1.12
      1 /*	$NetBSD: column.c,v 1.12 2005/02/17 17:17:25 xtraeme Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1989, 1993, 1994
      5  *	The Regents of the University of California.  All rights reserved.
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that the following conditions
      9  * are met:
     10  * 1. Redistributions of source code must retain the above copyright
     11  *    notice, this list of conditions and the following disclaimer.
     12  * 2. Redistributions in binary form must reproduce the above copyright
     13  *    notice, this list of conditions and the following disclaimer in the
     14  *    documentation and/or other materials provided with the distribution.
     15  * 3. Neither the name of the University nor the names of its contributors
     16  *    may be used to endorse or promote products derived from this software
     17  *    without specific prior written permission.
     18  *
     19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     29  * SUCH DAMAGE.
     30  */
     31 
     32 #include <sys/cdefs.h>
     33 #ifndef lint
     34 __COPYRIGHT("@(#) Copyright (c) 1989, 1993, 1994\n\
     35 	The Regents of the University of California.  All rights reserved.\n");
     36 #endif /* not lint */
     37 
     38 #ifndef lint
     39 #if 0
     40 static char sccsid[] = "@(#)column.c	8.4 (Berkeley) 5/4/95";
     41 #endif
     42 __RCSID("$NetBSD: column.c,v 1.12 2005/02/17 17:17:25 xtraeme Exp $");
     43 #endif /* not lint */
     44 
     45 #include <sys/types.h>
     46 #include <sys/ioctl.h>
     47 
     48 #include <ctype.h>
     49 #include <err.h>
     50 #include <termios.h>
     51 #include <limits.h>
     52 #include <stdio.h>
     53 #include <stdlib.h>
     54 #include <string.h>
     55 #include <unistd.h>
     56 
     57 void  c_columnate(void);
     58 void *emalloc(int);
     59 void  input(FILE *);
     60 void  maketbl(void);
     61 void  print(void);
     62 void  r_columnate(void);
     63 void  usage(void);
     64 
     65 int termwidth = 80;		/* default terminal width */
     66 
     67 int entries;			/* number of records */
     68 int eval;			/* exit value */
     69 int maxlength;			/* longest record */
     70 char **list;			/* array of pointers to records */
     71 const char *separator = "\t ";	/* field separator for table option */
     72 
     73 int
     74 main(int argc, char **argv)
     75 {
     76 	struct winsize win;
     77 	FILE *fp;
     78 	int ch, tflag, xflag;
     79 	const char *p;
     80 
     81 	if (ioctl(1, TIOCGWINSZ, &win) == -1 || !win.ws_col) {
     82 		if ((p = getenv("COLUMNS")) != NULL)
     83 			termwidth = atoi(p);
     84 	} else
     85 		termwidth = win.ws_col;
     86 
     87 	tflag = xflag = 0;
     88 	while ((ch = getopt(argc, argv, "c:s:tx")) != -1)
     89 		switch(ch) {
     90 		case 'c':
     91 			termwidth = atoi(optarg);
     92 			break;
     93 		case 's':
     94 			separator = optarg;
     95 			break;
     96 		case 't':
     97 			tflag = 1;
     98 			break;
     99 		case 'x':
    100 			xflag = 1;
    101 			break;
    102 		case '?':
    103 		default:
    104 			usage();
    105 		}
    106 	argc -= optind;
    107 	argv += optind;
    108 
    109 	if (!*argv)
    110 		input(stdin);
    111 	else for (; *argv; ++argv)
    112 		if ((fp = fopen(*argv, "r")) != NULL) {
    113 			input(fp);
    114 			(void)fclose(fp);
    115 		} else {
    116 			warn("%s", *argv);
    117 			eval = 1;
    118 		}
    119 
    120 	if (!entries)
    121 		exit(eval);
    122 
    123 	if (tflag)
    124 		maketbl();
    125 	else if (maxlength >= termwidth)
    126 		print();
    127 	else if (xflag)
    128 		c_columnate();
    129 	else
    130 		r_columnate();
    131 	exit(eval);
    132 }
    133 
    134 #define	TAB	8
    135 void
    136 c_columnate(void)
    137 {
    138 	int chcnt, col, cnt, endcol, numcols;
    139 	char **lp;
    140 
    141 	maxlength = (maxlength + TAB) & ~(TAB - 1);
    142 	numcols = termwidth / maxlength;
    143 	endcol = maxlength;
    144 	for (chcnt = col = 0, lp = list;; ++lp) {
    145 		chcnt += printf("%s", *lp);
    146 		if (!--entries)
    147 			break;
    148 		if (++col == numcols) {
    149 			chcnt = col = 0;
    150 			endcol = maxlength;
    151 			putchar('\n');
    152 		} else {
    153 			while ((cnt = ((chcnt + TAB) & ~(TAB - 1))) <= endcol) {
    154 				(void)putchar('\t');
    155 				chcnt = cnt;
    156 			}
    157 			endcol += maxlength;
    158 		}
    159 	}
    160 	if (chcnt)
    161 		putchar('\n');
    162 }
    163 
    164 void
    165 r_columnate(void)
    166 {
    167 	int base, chcnt, cnt, col, endcol, numcols, numrows, row;
    168 
    169 	maxlength = (maxlength + TAB) & ~(TAB - 1);
    170 	numcols = termwidth / maxlength;
    171 	numrows = entries / numcols;
    172 	if (entries % numcols)
    173 		++numrows;
    174 
    175 	for (row = 0; row < numrows; ++row) {
    176 		endcol = maxlength;
    177 		for (base = row, chcnt = col = 0; col < numcols; ++col) {
    178 			chcnt += printf("%s", list[base]);
    179 			if ((base += numrows) >= entries)
    180 				break;
    181 			while ((cnt = ((chcnt + TAB) & ~(TAB - 1))) <= endcol) {
    182 				(void)putchar('\t');
    183 				chcnt = cnt;
    184 			}
    185 			endcol += maxlength;
    186 		}
    187 		putchar('\n');
    188 	}
    189 }
    190 
    191 void
    192 print(void)
    193 {
    194 	int cnt;
    195 	char **lp;
    196 
    197 	for (cnt = entries, lp = list; cnt--; ++lp)
    198 		(void)printf("%s\n", *lp);
    199 }
    200 
    201 typedef struct _tbl {
    202 	char **list;
    203 	int cols, *len;
    204 } TBL;
    205 #define	DEFCOLS	25
    206 
    207 void
    208 maketbl(void)
    209 {
    210 	TBL *t;
    211 	int coloff, cnt;
    212 	char *p, **lp;
    213 	int *lens, *nlens, maxcols;
    214 	TBL *tbl;
    215 	char **cols, **ncols;
    216 
    217 	t = tbl = emalloc(entries * sizeof(TBL));
    218 	cols = emalloc((maxcols = DEFCOLS) * sizeof(char *));
    219 	lens = emalloc(maxcols * sizeof(int));
    220 	for (cnt = 0, lp = list; cnt < entries; ++cnt, ++lp, ++t) {
    221 		for (coloff = 0, p = *lp;
    222 		    (cols[coloff] = strtok(p, separator)) != NULL;
    223 		    p = NULL)
    224 			if (++coloff == maxcols) {
    225 				if (!(ncols = realloc(cols, (u_int)maxcols +
    226 				    DEFCOLS * sizeof(char *))) ||
    227 				    !(nlens = realloc(lens,
    228 				    (u_int)maxcols + DEFCOLS * sizeof(int))))
    229 					err(1, "realloc");
    230 				cols = ncols;
    231 				lens = nlens;
    232 				memset((char *)lens + maxcols * sizeof(int),
    233 				    0, DEFCOLS * sizeof(int));
    234 				maxcols += DEFCOLS;
    235 			}
    236 		t->list = emalloc(coloff * sizeof(char *));
    237 		t->len = emalloc(coloff * sizeof(int));
    238 		for (t->cols = coloff; --coloff >= 0;) {
    239 			t->list[coloff] = cols[coloff];
    240 			t->len[coloff] = strlen(cols[coloff]);
    241 			if (t->len[coloff] > lens[coloff])
    242 				lens[coloff] = t->len[coloff];
    243 		}
    244 	}
    245 	for (cnt = 0, t = tbl; cnt < entries; ++cnt, ++t) {
    246 		for (coloff = 0; coloff < t->cols  - 1; ++coloff)
    247 			(void)printf("%s%*s", t->list[coloff],
    248 			    lens[coloff] - t->len[coloff] + 2, " ");
    249 		(void)printf("%s\n", t->list[coloff]);
    250 	}
    251 }
    252 
    253 #define	DEFNUM		1000
    254 #define	MAXLINELEN	(LINE_MAX + 1)
    255 
    256 void
    257 input(FILE *fp)
    258 {
    259 	static int maxentry;
    260 	int len;
    261 	char *p, buf[MAXLINELEN];
    262 	char **n;
    263 
    264 	if (!list)
    265 		list = emalloc((maxentry = DEFNUM) * sizeof(char *));
    266 	while (fgets(buf, MAXLINELEN, fp)) {
    267 		for (p = buf; *p && isspace((unsigned char)*p); ++p);
    268 		if (!*p)
    269 			continue;
    270 		if (!(p = strchr(p, '\n'))) {
    271 			warnx("line too long");
    272 			eval = 1;
    273 			continue;
    274 		}
    275 		*p = '\0';
    276 		len = p - buf;
    277 		if (maxlength < len)
    278 			maxlength = len;
    279 		if (entries == maxentry) {
    280 			maxentry += DEFNUM;
    281 			if (!(n = realloc(list,
    282 			    (u_int)maxentry * sizeof(char *))))
    283 				err(1, "realloc");
    284 			list = n;
    285 		}
    286 		list[entries++] = strdup(buf);
    287 	}
    288 }
    289 
    290 void *
    291 emalloc(int size)
    292 {
    293 	char *p;
    294 
    295 	if (!(p = malloc(size)))
    296 		err(1, "malloc");
    297 	memset(p, 0, size);
    298 	return (p);
    299 }
    300 
    301 void
    302 usage(void)
    303 {
    304 
    305 	(void)fprintf(stderr,
    306 	    "usage: column [-tx] [-c columns] [-s sep] [file ...]\n");
    307 	exit(1);
    308 }
    309