cterminalncursesxtermansi-escape

Reading the Device Status Report ANSI escape sequence reply


I'm trying to retrieve the coordinates of cursor in a VT100 terminal using the following code:

void getCursor(int* x, int* y) {
  printf("\033[6n");
   scanf("\033[%d;%dR", x, y);
}

I'm using the following ANSI escape sequence:

Device Status Report - ESC[6n

Reports the cursor position to the application as (as though typed at the keyboard) ESC[n;mR, where n is the row and m is the column.

The code compiles and the ANSI sequence is sent, but, upon receiving it, the terminal prints the ^[[x;yR string to the stdout instead of stdin making it imposible for me to retrieve it from the program:

terminal window

Clearly, the string is designated for the program, though, so I must be doing something incorrectly. Does anybody know what it is?


Solution

  • Your program is working but is waiting for an EOL character.

    scanf is line oriented so it waits for a new line before processing. Try running your program and then hit the enter key.

    The solution is to use something else that doesn't need a new line to read the input and then use sscanf to parse the values out.

    You will also need to make stdin non-blocking or you won't get the input until the buffer is full or stdin is closed. See this question Making stdin non-blocking

    You should also call fflush(stdout); after your printf to ensure it is actually written (printf is often line buffered so without a newline it may not flush the buffer).