blob: 3b5a68cd859b35e84e92488ecdaa20dd1921854f [file] [log] [blame]
bigbiff bigbiffe60683a2013-02-22 20:55:50 -05001/*
2 * No copyright is claimed. This code is in the public domain; do with
3 * it what you wish.
4 *
5 * Written by Karel Zak <kzak@redhat.com>
6 */
7#include <ctype.h>
8
9#include "c.h"
10#include "ttyutils.h"
11
12int get_terminal_width(void)
13{
14#ifdef TIOCGSIZE
15 struct ttysize t_win;
16#endif
17#ifdef TIOCGWINSZ
18 struct winsize w_win;
19#endif
20 const char *cp;
21
22#ifdef TIOCGSIZE
23 if (ioctl (0, TIOCGSIZE, &t_win) == 0)
24 return t_win.ts_cols;
25#endif
26#ifdef TIOCGWINSZ
27 if (ioctl (0, TIOCGWINSZ, &w_win) == 0)
28 return w_win.ws_col;
29#endif
30 cp = getenv("COLUMNS");
31 if (cp) {
32 char *end = NULL;
33 long c;
34
35 errno = 0;
36 c = strtol(cp, &end, 10);
37
38 if (errno == 0 && end && *end == '\0' && end > cp &&
39 c > 0 && c <= INT_MAX)
40 return c;
41 }
42 return 0;
43}
44
45int get_terminal_name(const char **path,
46 const char **name,
47 const char **number)
48{
49 const char *tty;
50 const char *p;
51
52 if (name)
53 *name = NULL;
54 if (path)
55 *path = NULL;
56 if (number)
57 *number = NULL;
58
59 tty = ttyname(STDERR_FILENO);
60 if (!tty)
61 return -1;
62 if (path)
63 *path = tty;
64 tty = strncmp(tty, "/dev/", 5) == 0 ? tty + 5 : tty;
65 if (name)
66 *name = tty;
67 if (number) {
68 for (p = tty; p && *p; p++) {
69 if (isdigit(*p)) {
70 *number = p;
71 break;
72 }
73 }
74 }
75 return 0;
76}
77
78
79#ifdef TEST_PROGRAM
80# include <stdlib.h>
81int main(void)
82{
83 const char *path, *name, *num;
84
85 if (get_terminal_name(&path, &name, &num) == 0) {
86 fprintf(stderr, "tty path: %s\n", path);
87 fprintf(stderr, "tty name: %s\n", name);
88 fprintf(stderr, "tty number: %s\n", num);
89 }
90 fprintf(stderr, "tty width: %d\n", get_terminal_width());
91
92 return EXIT_SUCCESS;
93}
94#endif