Add COLUMNS support to cols(1)

First attempt to see if COLUMNS is set, if that fails an ioctl()
is issued to find the width of the output device.  If that fails
as well, we default to 65 chars per line.
This commit is contained in:
sin 2015-02-19 11:24:28 +00:00
parent 8c041cd115
commit 9355d88aae
2 changed files with 17 additions and 7 deletions

18
cols.1
View File

@ -1,4 +1,4 @@
.Dd February 1, 2015 .Dd February 19, 2015
.Dt COLS 1 .Dt COLS 1
.Os sbase .Os sbase
.Sh NAME .Sh NAME
@ -20,16 +20,24 @@ character columns. If no
is given, is given,
.Nm .Nm
reads from stdin. reads from stdin.
.Pp
By default
.Nm cols
tries to figure out the width of the output
device. If that fails, it defaults to 65 chars.
.Sh OPTIONS .Sh OPTIONS
.Bl -tag -width Ds .Bl -tag -width Ds
.It Fl c Ar chars .It Fl c Ar chars
Set the maximum number of character columns to use Set the maximum number of character columns to use
(unless the input contains lines longer than (unless the input contains lines longer than
.Ar num .Ar num
characters). By default characters).
.Nm cols .El
tries to figure out the width of the output .Sh ENVIRONMENT
device. If that fails, it defaults to 65 chars. .Bl -tag -width COLUMNS
.It COLUMNS
If this variable is set, the value is used as the
width of the output device.
.El .El
.Sh HISTORY .Sh HISTORY
.Nm .Nm

6
cols.c
View File

@ -31,6 +31,7 @@ main(int argc, char *argv[])
size_t i, l, col, len, bytes, maxlen = 0; size_t i, l, col, len, bytes, maxlen = 0;
struct winsize w; struct winsize w;
FILE *fp; FILE *fp;
char *p;
ARGBEGIN { ARGBEGIN {
case 'c': case 'c':
@ -42,8 +43,9 @@ main(int argc, char *argv[])
} ARGEND; } ARGEND;
if (cflag == 0) { if (cflag == 0) {
ioctl(STDOUT_FILENO, TIOCGWINSZ, &w); if ((p = getenv("COLUMNS")))
if (w.ws_col != 0) chars = estrtonum(p, 1, MIN(LLONG_MAX, SIZE_MAX));
else if (!ioctl(STDOUT_FILENO, TIOCGWINSZ, &w) && w.ws_col > 0)
chars = w.ws_col; chars = w.ws_col;
} }