Skip to content

Instantly share code, notes, and snippets.

@m1lkweed
Created July 14, 2022 16:26
Show Gist options
  • Save m1lkweed/0ef89ee1d93f3f06ea0fcef38dbae3a8 to your computer and use it in GitHub Desktop.
Save m1lkweed/0ef89ee1d93f3f06ea0fcef38dbae3a8 to your computer and use it in GitHub Desktop.
Get the position of the tty cursor
#include <stdio.h>
#include <unistd.h>
#include <termios.h>
int get_pos(int *col, int *line){
char buf[30]={0};
int ret, i, pow;
char ch;
*line = 0;
*col = 0;
struct termios term, restore;
tcgetattr(0, &term);
tcgetattr(0, &restore);
term.c_lflag &= ~(ICANON|ECHO);
tcsetattr(0, TCSANOW, &term);
write(1, "\x1b[6n", 4);
for( i = 0, ch = 0; ch != 'R'; ++i){
ret = read(0, &ch, 1);
if(!ret){
tcsetattr(0, TCSANOW, &restore);
return 1;
}
buf[i] = ch;
}
if(i < 2){
tcsetattr(0, TCSANOW, &restore);
return 1;
}
for(i -= 2, pow = 1; buf[i] != ';'; --i, pow *= 10)
*col = *col + (buf[i] - '0') * pow;
for(--i, pow = 1; buf[i] != '['; --i, pow *= 10)
*line = *line + ( buf[i] - '0' ) * pow;
tcsetattr(0, TCSANOW, &restore);
return 0;
}
int main(){
int x, y;
if(!get_pos(&x, &y))
printf("col: %d, line: %d\n", x, y);
else
puts("Could not get position of the tty cursor");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment