To fetch the size, the correct way is to call the TIOCGWINSZ
ioctl()
. An example from my code:
struct winsize ws = { 0, 0, 0, 0 };
if(ioctl(tt->outfd, TIOCGWINSZ, &ws) == -1)
return;
/* ws.ws_row and ws.ws_col now give the size */
You'll want to do that initially, and then again after receipt of a SIGWINCH
signal, which informs of a WINdow CHange.
As for obtaining the cursor position, that's a little harder. Some terminals allow querying it by DSR 6 (Device Status Report)
$ echo -ne "\e[6n"; cat -v
^[[62;1R
The reply from DSR comes in CSI R, here telling me the (1-based) 62nd row, 1st column.
However, since not all terminals support DSR 6, it may be easiest not to rely on being able to query the cursor position, and instead performing your initial terminal addressing in an absolute manner, placing the cursor exactly where you want it.