簡體   English   中英

如何使用 ascii 轉義序列在 c 中獲取終端 cursor position

[英]How can I get terminal cursor position in c with ascii escape sequence

我想用 ansi 轉義序列代碼獲得終端 cursor position。 我看到了這個 來源,我以為我可以獲得終端 cursor position 但是當我嘗試 c 時我什至無法獲得這個變量。

我試過這段代碼:

#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 依賴代碼。 我研究了所有相關的 stackoverflow 主題,但沒有看到答案。 您也可以推薦另一種我不想使用基於庫或操作系統的代碼的方法。 我目前正在努力在 c 中創建一個終端應用程序,如果我能獲得終端 cursor position 那就太好了。

我用 termios.h 庫解決了這個問題。 我沒有使用 ncurses。 我在這里找到了解決方案。

#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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM