0

I am trying to get the caret's (console cursor) position in ubuntu. I found a solution (here: https://thoughtsordiscoveries.wordpress.com/2017/04/26/set-and-read-cursor-position-in-terminal-windows-and-linux/ ) that makes use of ANSI codes, which looks like this:

printf("\033[6n");
scanf("\033[%d;%dR", &x, &y); // in x and y I save the position

The problem with this is that printf("\033[6n"); prints stuff in the terminal, which is not something that I want. I tried to hide the output of printf("\033[6n"); using the ANSI code \033[8m, but this only makes the characters invisible, which is not what I want. I want to get rid of the output completely. I know that you can redirect the output to /dev/null if I'm not mistaking, but I don't know if that won't mess up the cursor position then, I didn't try this yet.

So, one of the two options:

1. How can I hide the output of printf without messing up anything?

OR

2. Is there any other way to get the cursor position without external libraries? I believe it is possible with <termios.h>, but I couldn't find an explanation on how that works.

H-005
  • 467
  • 3
  • 15
  • `prints stuff in the terminal` What does it print exactly? `without external libraries in C/C++ on linux?` Why without external libraries? Why not use ncurses? Basically you want to do the same as [this bash code](https://stackoverflow.com/a/2575525/9072753) but in C. – KamilCuk Apr 19 '21 at 13:21
  • @KamilCuk By "prints stuff in the terminal" I mean that `printf(\033[6n");"` prints `^[[45;1R` for example, if the cursor is at `x = 45` and `y = 1`. And no external libraries because I'm trying to do this by myself, it's not for something important, just personal knowledge – H-005 Apr 19 '21 at 14:53

1 Answers1

1

On my terminal disabling ECHO and disable canonical mode, but setting terminal to RAW is probably just better. Following code misses a lot of error handling:

#include <stdio.h>
#include <termios.h>
#include <unistd.h>
#include <fcntl.h>    
int main() {
    int x, y;
    int t = STDOUT_FILENO;
    struct termios sav;
    tcgetattr(t, &sav);
    struct termios opt = sav;
    opt.c_lflag &= ~(ECHO | ICANON);
    // but better just cfmakeraw(&opt);
    tcsetattr(t, TCSANOW, &opt);
    printf("\033[6n");
    fflush(stdout);
    scanf("\033[%d;%dR", &x, &y);
    tcsetattr(t, TCSANOW, &sav);
    printf("Cursor pos is %d %d\n", x, y);
}
KamilCuk
  • 120,984
  • 8
  • 59
  • 111