Click to See Complete Forum and Search --> : need to get the terminal size


bsamuels
11-12-2003, 11:36 AM
I see that stty size will return the size of the terminal window, but how do I get this info inside of a program. I want to write a simple pong-like game and need the borders, but would like to calculate them dynamically.

goon12
11-12-2003, 12:06 PM
I know you can get that using ncurses. I will attach a sample on here.

It might be a little more in there but it tells you the size of your terminal. Note lines 49 and 50:

printw("Cols: %d\t", COLS);
printw("LINES: %d\n", LINES);


more:
http://www.crankhouse.com/ncht/


-goon12

bsamuels
11-12-2003, 06:55 PM
why would I return 0 with a call to either LINES or COLS?
Just trying to use the values and I get 0?!

bwkaz
11-12-2003, 07:42 PM
Are you using C, or some other language?

It's much harder than it's worth if you're using C to try to parse the output of stty (it's simple if you're using shell or Perl...). But you can use atoi(getenv("COLUMNS")); and atoi(getenv("LINES"));, as bash seems to set both of those variables appropriately.

bsamuels
11-12-2003, 08:08 PM
I am using C and not in a script but rather in a system programming environment

bsamuels
11-12-2003, 08:24 PM
Tried atoi(getenv("LINES")) and got a Segmentation fault

bwkaz
11-12-2003, 10:15 PM
Hmm... maybe bash doesn't always set it?

Store the result of getenv("LINES") into a char * variable. If it's not NULL, then call atoi() on it. If the result of getenv is NULL, then the LINES variable is not in fact set. This could be because you're not running the program from a shell. (You need to be running it from a shell, not just a terminal emulator. If in doubt, start up an xterm and then start the program from inside the xterm window.)

goon12
11-13-2003, 12:59 AM
Originally posted by bsamuels
why would I return 0 with a call to either LINES or COLS?
Just trying to use the values and I get 0?!

If you do use ncurses to do it, you have to do something like


#include<ncurses.h>

int main( void )
{
int lines;
int cols;
initscr();
lines = LINES;
cols = COLS;
endwin();
printf("Lines: %d\nCols %d\n",lines, cols);

return 0;
}


-goon12

binaryDigit
11-15-2003, 03:05 PM
i believe you can also use the term.h library and use the functions
tigetnum("lines");
and
tigetnum("cols");