-2

I want to get terminal cursor position with ansi escape sequence codes. I saw this source and I thought I can get terminal cursor position but when I try in c I can't even get this variables.

I tried this code:

#include <stdio.h>

int main()
{
   printf("\033[%d;%dH", 10, 11); // I set cursor position to x=10, y=11
   printf("\033[6n"); // This only print like '^[[11;10R'
   scanf("\033[%d;%dR", x, y); // It didn't even worked
   printf("\n%d, %d\n", x, y); // Also didn't worked

   return 0;
}

I don't want to use ncurses library or windows/linux dependency codes. I research in all revelant stackoverflow topics but I didn't see an answer. Also you can recommend another ways I just don't want to use library or os based codes. I'm currently working to make a terminal application in c if I can get terminal cursor position it would be great.

  • 1
    "Please wash me, but don't make me wet." :-D Any C program uses at least the standard library of its compiler system. -- Such escape codes work with certain terminal emulations. Did you set your terminal to ANSI emulation? What OS are you using, and what terminal? For example, if you have a primitive terminal like Windows' cmd, you _need_ to call Win32 API functions. – the busybee Sep 27 '22 at 20:18

1 Answers1

0

I solved this problem with termios.h library. I didn't use ncurses. I found the solution in here.

#include <stdio.h>
#include <termios.h>

int
main() {
 int x = 0, y = 0;
 get_pos(&y, &x);
 printf("x:%d, y:%d\n", x, y);
 return 0;
}

int
get_pos(int *y, int *x) {

 char buf[30]={0};
 int ret, i, pow;
 char ch;

*y = 0; *x = 0;

 struct termios term, restore;

 tcgetattr(0, &term);
 tcgetattr(0, &restore);
 term.c_lflag &= ~(ICANON|ECHO);
 tcsetattr(0, TCSANOW, &term);

 write(1, "\033[6n", 4);

 for( i = 0, ch = 0; ch != 'R'; i++ )
 {
    ret = read(0, &ch, 1);
    if ( !ret ) {
       tcsetattr(0, TCSANOW, &restore);
       fprintf(stderr, "getpos: error reading response!\n");
       return 1;
    }
    buf[i] = ch;
    printf("buf[%d]: \t%c \t%d\n", i, ch, ch);
 }

 if (i < 2) {
    tcsetattr(0, TCSANOW, &restore);
    printf("i < 2\n");
    return(1);
 }

 for( i -= 2, pow = 1; buf[i] != ';'; i--, pow *= 10)
     *x = *x + ( buf[i] - '0' ) * pow;

 for( i-- , pow = 1; buf[i] != '['; i--, pow *= 10)
     *y = *y + ( buf[i] - '0' ) * pow;

 tcsetattr(0, TCSANOW, &restore);
 return 0;
}