| 1 |
Description: properly check terminal width |
| 2 |
Author: Baruch Even <[email protected]> |
| 3 |
|
| 4 |
--- a/bidiv.c |
| 5 |
+++ b/bidiv.c |
| 6 |
@@ -32,6 +32,8 @@ |
| 7 |
#include <string.h> |
| 8 |
#endif |
| 9 |
|
| 10 |
+#include "term.h" |
| 11 |
+ |
| 12 |
char *progname; |
| 13 |
|
| 14 |
int width=80; |
| 15 |
@@ -235,23 +237,15 @@ int |
| 16 |
main(int argc, char *argv[]) |
| 17 |
{ |
| 18 |
FILE *fp; |
| 19 |
- char *s; |
| 20 |
- int i,c; |
| 21 |
+ int c; |
| 22 |
int status=0; |
| 23 |
|
| 24 |
/* TODO: get width from tty setup, COLUMNS variable, and/or |
| 25 |
command line option */ |
| 26 |
progname=argv[0]; |
| 27 |
|
| 28 |
- /* The COLUMNS variable (set by zsh and bash, for example) |
| 29 |
- overrides the default 'width'. |
| 30 |
- TODO: also try to read the column number directly from the tty. |
| 31 |
- */ |
| 32 |
- if((s=getenv("COLUMNS"))){ |
| 33 |
- i=atoi(s); |
| 34 |
- if(i>0) |
| 35 |
- width=i; |
| 36 |
- } |
| 37 |
+ /* Read the size from the tty or the COLUMNS var, default to 80 otherwise */ |
| 38 |
+ width = term_size_get(); |
| 39 |
|
| 40 |
#ifdef HAVE_LOCALE |
| 41 |
setlocale(LC_CTYPE, ""); |
| 42 |
--- /dev/null |
| 43 |
+++ b/term.h |
| 44 |
@@ -0,0 +1,9 @@ |
| 45 |
+#ifndef _TERM_H_ |
| 46 |
+#define _TERM_H_ |
| 47 |
+ |
| 48 |
+/* Returns terminal size, attempt to get it from tty, COLUMNS or default to 80 |
| 49 |
+ * otherwise |
| 50 |
+ */ |
| 51 |
+int term_size_get(void); |
| 52 |
+ |
| 53 |
+#endif |
| 54 |
--- /dev/null |
| 55 |
+++ b/term.c |
| 56 |
@@ -0,0 +1,22 @@ |
| 57 |
+#include <sys/ioctl.h> |
| 58 |
+#include <stdlib.h> |
| 59 |
+#include <limits.h> |
| 60 |
+#include "term.h" |
| 61 |
+ |
| 62 |
+int term_size_get(void) |
| 63 |
+{ |
| 64 |
+ struct winsize win; |
| 65 |
+ int cols; |
| 66 |
+ char *col_str; |
| 67 |
+ int err; |
| 68 |
+ |
| 69 |
+ err = ioctl(1, TIOCGWINSZ, (char *)&win); |
| 70 |
+ if (err != -1 && win.ws_col > 0) |
| 71 |
+ return win.ws_col; |
| 72 |
+ |
| 73 |
+ col_str = getenv("COLUMNS"); |
| 74 |
+ if (!col_str || (cols = atoi(col_str)) <= 0 || cols == INT_MAX) |
| 75 |
+ cols = 80; |
| 76 |
+ |
| 77 |
+ return cols; |
| 78 |
+} |