Getting cursor position and terminal size in linux terminal

In my Linux C ++ console application, I want to get the size of the terminal (rows + columns) and the current cursor position. For the latter, I think I could use ANSI codes for this, but I'm not sure how to parse it correctly. Also I do not see how to get the window size?

For other reasons, switching to ncurses is currently not an option.

+4
source share
2 answers

The old method of getting size was termcap with libtermcap. The new one is terminfo (+ lib). I would recommend using a library that abstracts this (and all other terminal-related stuff) and uses an output library such as (n) curses.

This will also work on other Unix systems.

+2
source

To get the size, the correct way is to call 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 will want to do this first, and then again after receiving a SIGWINCH signal that reports a WINDOW CHange.

As for getting the cursor position, this is a little trickier. Some terminals allow you to request it using DSR 6 (device status report)

 $ echo -ne "\e[6n"; cat -v ^[[62;1R 

The answer from DSR comes in CSI R, it tells me the (1st) 62nd row, 1st column.

However, since not all terminals support DSR 6, it may be easiest not to rely on the ability to request the cursor position and instead perform absolute addressing of the final address by placing the cursor where you want.

+1
source

Source: https://habr.com/ru/post/1402603/


All Articles