如何使用ANSI代码在C中获取光标位置 [英] How to get cursor position in C using ANSI code
本文介绍了如何使用ANSI代码在C中获取光标位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图从一个小的c程序中获取光标位置,因此在进行谷歌搜索之后,我发现了此ANSI代码\x1b[6n
.它应该返回光标的x和y位置(如果我没记错的话)
所以
printf("\x1b[6n");
给我输出:;1R
我无法理解x和y位置的输出.
I am trying to get cursor position from a little c program so after googling I found this ANSI code \x1b[6n
. It should return x and y location of cursor ( if I am not wrong)
So
printf("\x1b[6n");
is giving me output : ;1R
I can't understand the output in terms of x and y location.
平台是Linux(xterm)
Edit : Platform is Linux (xterm)
推荐答案
#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;
}
这篇关于如何使用ANSI代码在C中获取光标位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文