24

How do I find the terminal width & height of an ncurses application?

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
DylanJ
  • 2,373
  • 3
  • 25
  • 24

5 Answers5

28

void getmaxyx(WINDOW *win, int y, int x); i believe...

also, this may help...

Getting terminal width in C?

Community
  • 1
  • 1
mtvee
  • 1,585
  • 13
  • 13
  • 1
    Also: Don't forget that some operating systems have SIGWINCH which your process receives when the terminal is resized... – asveikau Nov 28 '09 at 08:46
  • `initscr()` will clear screen. Is there any way which can get terminal size and don't clear screen? – jiandingzhe Oct 24 '14 at 08:55
  • 1
    Not sure this is true because `y` & `x` are not pointers and therefore the function will not copy anything to them. And from `mkssoftware.com` : "`getbegyx() and getmaxyx() macros store the current beginning coordinates and size of the specified window.`" – Karim Manaouil Aug 27 '17 at 23:59
  • 4
    @afr0ck As your quote states, those are all macros, so `y` and `x` do not need to be pointers. The macro works directly on the given variables, with no copy-assignment or pointers needed. – Shelby Oldfield Aug 31 '17 at 23:20
18

ncurses applications normally handle SIGWINCH and use the ioctl with TIOCGWINSZ to obtain the system's notion of the screensize. That may be overridden by the environment variables LINES and COLUMNS (see use_env).

Given that, the ncurses global variables LINES and COLS are updated as a side-effect when wgetch returns KEY_RESIZE (in response to a SIGWINCH) to give the size of stdscr (the standard screen representing the whole terminal).

You can of course use getmaxx, getmaxy and getmaxyx to get one or both of the limits for the x- and y-ordinates of a window. Only the last is standard (and portable).

Further reading:

Thomas Dickey
  • 51,086
  • 7
  • 70
  • 105
3

i'm using this code:

struct winsize size;
if (ioctl(0, TIOCGWINSZ, (char *) &size) < 0)
    printf("TIOCGWINSZ error");
printf("%d rows, %d columns\n", size.ws_row, size.ws_col);
qknight
  • 866
  • 10
  • 23
  • 1
    That's not very ncurses'ish. – einpoklum Feb 28 '16 at 12:08
  • Yes I used to... until I try to redirect or use a IDE like Netbeans... in those cases, the file descriptor must be changed (in case of redirecting from stdin, use STDOUT_FILENO; and using a IDE it's tricky when debugging/stepping you MUST have the "output" window opened). – Hurukan Imperial Stepper May 17 '22 at 10:15
1

What about using SCR_H and SCR_W?

Conrad Meyer
  • 2,851
  • 21
  • 24
1

the variables COLS, LINES are initialized to the screen sizes after initscr().

Source: NCURSES Programming HOWTO

I'm not sure if they get updated on resize though.

Bora M. Alper
  • 3,538
  • 1
  • 24
  • 35