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