首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用ascii转义序列在c中获得终端光标位置?

如何使用ascii转义序列在c中获得终端光标位置?
EN

Stack Overflow用户
提问于 2022-09-27 19:06:36
回答 1查看 103关注 0票数 -2

我想用ansi转义序列代码得到终端光标的位置。我看到了这个来源,我想我可以得到终端光标的位置,但是当我尝试使用c语言时,我甚至不能得到这个变量。

我试过这个代码:

代码语言:javascript
复制
#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;
}

我不想使用ncurses库或windows/linux依赖项代码。我研究了所有狂欢的堆积如山的话题,但我没有看到答案。此外,您也可以推荐另一种方法,我只是不想使用库或基于操作系统的代码。我目前正在用c语言开发一个终端应用程序,如果我能得到终端光标的位置,那就太好了。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-10-01 08:01:49

我用白蚁图书馆解决了这个问题。我没有用诅咒。我在这里中找到了解决方案。

代码语言:javascript
复制
#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;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73872672

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档