5

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

For other reasons switching to ncurses is not an option at this time.

fasel
  • 53
  • 1
  • 4
  • Have you looked at this solution? http://stackoverflow.com/a/1022961/522150 And this http://stackoverflow.com/a/1023006/522150. They solve the terminal lines and columns problem well. – JWL Mar 21 '12 at 07:15

2 Answers2

2

Old method of getting the size was termcap with the libtermcap. New is terminfo (+lib). I would recommend to use a library that abstracts this (and all other terminal related stuff) away and use a terminal output library like (n)curses.

This will in addition also work on other Unix systems.

flolo
  • 15,148
  • 4
  • 32
  • 57
1

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.

LeoNerd
  • 8,344
  • 1
  • 29
  • 36