Home | History | Annotate | Line # | Download | only in column
column.c revision 1.15
      1 /*	$NetBSD: column.c,v 1.15 2006/08/26 18:17:41 christos 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.15 2006/08/26 18:17:41 christos 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 #include <util.h>
     57 
     58 #define	TAB	8
     59 
     60 static void  c_columnate(void);
     61 static void  input(FILE *);
     62 static void  maketbl(void);
     63 static void  print(void);
     64 static void  r_columnate(void);
     65 static void  usage(void) __attribute__((__noreturn__));
     66 
     67 static int termwidth = 80;		/* default terminal width */
     68 
     69 static int entries;			/* number of records */
     70 static int eval;			/* exit value */
     71 static int maxlength;			/* longest record */
     72 static char **list;			/* array of pointers to records */
     73 static const char *separator = "\t ";	/* field separator for table option */
     74 
     75 int
     76 main(int argc, char **argv)
     77 {
     78 	struct winsize win;
     79 	FILE *fp;
     80 	int ch, tflag, xflag;
     81 	const char *p;
     82 
     83 	setprogname(*argv);
     84 
     85 	if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) == -1 || !win.ws_col) {
     86 		if ((p = getenv("COLUMNS")) != NULL)
     87 			termwidth = atoi(p);
     88 	} else
     89 		termwidth = win.ws_col;
     90 
     91 	tflag = xflag = 0;
     92 	while ((ch = getopt(argc, argv, "c:s:tx")) != -1)
     93 		switch(ch) {
     94 		case 'c':
     95 			termwidth = atoi(optarg);
     96 			break;
     97 		case 's':
     98 			separator = optarg;
     99 			break;
    100 		case 't':
    101 			tflag = 1;
    102 			break;
    103 		case 'x':
    104 			xflag = 1;
    105 			break;
    106 		case '?':
    107 		default:
    108 			usage();
    109 		}
    110 	argc -= optind;
    111 	argv += optind;
    112 
    113 	if (!*argv)
    114 		input(stdin);
    115 	else for (; *argv; ++argv)
    116 		if ((fp = fopen(*argv, "r")) != NULL) {
    117 			input(fp);
    118 			(void)fclose(fp);
    119 		} else {
    120 			warn("Cannot open `%s'", *argv);
    121 			eval = 1;
    122 		}
    123 
    124 	if (!entries)
    125 		return eval;
    126 
    127 	maxlength = (maxlength + TAB) & ~(TAB - 1);
    128 	if (tflag)
    129 		maketbl();
    130 	else if (maxlength >= termwidth)
    131 		print();
    132 	else if (xflag)
    133 		c_columnate();
    134 	else
    135 		r_columnate();
    136 	return eval;
    137 }
    138 
    139 static void
    140 c_columnate(void)
    141 {
    142 	int chcnt, col, cnt, endcol, numcols;
    143 	char **lp;
    144 
    145 	numcols = termwidth / maxlength;
    146 	endcol = maxlength;
    147 	for (chcnt = col = 0, lp = list;; ++lp) {
    148 		chcnt += printf("%s", *lp);
    149 		if (!--entries)
    150 			break;
    151 		if (++col == numcols) {
    152 			chcnt = col = 0;
    153 			endcol = maxlength;
    154 			(void)putchar('\n');
    155 		} else {
    156 			while ((cnt = ((chcnt + TAB) & ~(TAB - 1))) <= endcol) {
    157 				(void)putchar('\t');
    158 				chcnt = cnt;
    159 			}
    160 			endcol += maxlength;
    161 		}
    162 	}
    163 	if (chcnt)
    164 		(void)putchar('\n');
    165 }
    166 
    167 static void
    168 r_columnate(void)
    169 {
    170 	int base, chcnt, cnt, col, endcol, numcols, numrows, row;
    171 
    172 	numcols = termwidth / maxlength;
    173 	numrows = entries / numcols;
    174 	if (entries % numcols)
    175 		++numrows;
    176 
    177 	for (row = 0; row < numrows; ++row) {
    178 		endcol = maxlength;
    179 		for (base = row, chcnt = col = 0; col < numcols; ++col) {
    180 			chcnt += printf("%s", list[base]);
    181 			if ((base += numrows) >= entries)
    182 				break;
    183 			while ((cnt = ((chcnt + TAB) & ~(TAB - 1))) <= endcol) {
    184 				(void)putchar('\t');
    185 				chcnt = cnt;
    186 			}
    187 			endcol += maxlength;
    188 		}
    189 		(void)putchar('\n');
    190 	}
    191 }
    192 
    193 static void
    194 print(void)
    195 {
    196 	int cnt;
    197 	char **lp;
    198 
    199 	for (cnt = entries, lp = list; cnt--; ++lp)
    200 		(void)printf("%s\n", *lp);
    201 }
    202 
    203 typedef struct _tbl {
    204 	char **list;
    205 	int cols, *len;
    206 } TBL;
    207 #define	DEFCOLS	25
    208 
    209 static void
    210 maketbl(void)
    211 {
    212 	TBL *t;
    213 	int coloff, cnt;
    214 	char *p, **lp;
    215 	int *lens, *nlens, maxcols;
    216 	TBL *tbl;
    217 	char **cols, **ncols;
    218 
    219 	t = tbl = emalloc(entries * sizeof(TBL));
    220 	cols = emalloc((maxcols = DEFCOLS) * sizeof(char *));
    221 	lens = emalloc(maxcols * sizeof(int));
    222 	for (cnt = 0, lp = list; cnt < entries; ++cnt, ++lp, ++t) {
    223 		for (coloff = 0, p = *lp;
    224 		    (cols[coloff] = strtok(p, separator)) != NULL;
    225 		    p = NULL)
    226 			if (++coloff == maxcols) {
    227 				ncols = erealloc(cols, maxcols +
    228 				    DEFCOLS * sizeof(char *));
    229 				nlens = erealloc(lens, maxcols +
    230 				    DEFCOLS * sizeof(int));
    231 				cols = ncols;
    232 				lens = nlens;
    233 				(void)memset((char *)(void *)lens + maxcols *
    234 				    sizeof(int), 0, DEFCOLS * sizeof(int));
    235 				maxcols += DEFCOLS;
    236 			}
    237 		t->list = emalloc(coloff * sizeof(char *));
    238 		t->len = emalloc(coloff * sizeof(int));
    239 		for (t->cols = coloff; --coloff >= 0;) {
    240 			t->list[coloff] = cols[coloff];
    241 			t->len[coloff] = strlen(cols[coloff]);
    242 			if (t->len[coloff] > lens[coloff])
    243 				lens[coloff] = t->len[coloff];
    244 		}
    245 	}
    246 	for (cnt = 0, t = tbl; cnt < entries; ++cnt, ++t) {
    247 		for (coloff = 0; coloff < t->cols  - 1; ++coloff)
    248 			(void)printf("%s%*s", t->list[coloff],
    249 			    lens[coloff] - t->len[coloff] + 2, " ");
    250 		(void)printf("%s\n", t->list[coloff]);
    251 	}
    252 	free(tbl);
    253 	free(cols);
    254 	free(lens);
    255 }
    256 
    257 #define	DEFNUM		1000
    258 #define	MAXLINELEN	(LINE_MAX + 1)
    259 
    260 static void
    261 input(FILE *fp)
    262 {
    263 	static int maxentry;
    264 	int len;
    265 	char *p, buf[MAXLINELEN];
    266 	char **n;
    267 
    268 	if (!list)
    269 		list = emalloc((maxentry = DEFNUM) * sizeof(char *));
    270 	while (fgets(buf, MAXLINELEN, fp)) {
    271 		for (p = buf; *p && isspace((unsigned char)*p); ++p);
    272 		if (!*p)
    273 			continue;
    274 		if (!(p = strchr(p, '\n'))) {
    275 			warnx("line too long");
    276 			eval = 1;
    277 			continue;
    278 		}
    279 		*p = '\0';
    280 		len = p - buf;
    281 		if (maxlength < len)
    282 			maxlength = len;
    283 		if (entries == maxentry) {
    284 			maxentry += DEFNUM;
    285 			n = erealloc(list, maxentry * sizeof(char *));
    286 			list = n;
    287 		}
    288 		list[entries++] = estrdup(buf);
    289 	}
    290 }
    291 
    292 static void
    293 usage(void)
    294 {
    295 
    296 	(void)fprintf(stderr,
    297 	    "Usage: %s [-tx] [-c columns] [-s sep] [file ...]\n",
    298 	    getprogname());
    299 	exit(1);
    300 }
    301