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