如何在 Linux 上的 C/C++ 中没有外部库的情况下获得插入符号位置?

问题描述

我试图在 ubuntu 中获取插入符号(控制台光标)的位置。我找到了一个使用 ANSI 代码解决方案(此处:https://thoughtsordiscoveries.wordpress.com/2017/04/26/set-and-read-cursor-position-in-terminal-windows-and-linux/),如下所示:

printf("\033[6n");
scanf("\033[%d;%dR",&x,&y); // in x and y I save the position

问题在于 printf("\033[6n"); 在终端中打印内容,这不是我想要的。我试图使用 ANSI 代码 printf("\033[6n"); 隐藏 \033[8m输出,但这只会使字符不可见,这不是我想要的。我想完全摆脱输出。我知道如果我没记错的话,您可以将输出重定向/dev/null,但我不知道这是否会弄乱光标位置,我还没有尝试过。

所以,两个选项之一:

1.如何隐藏 printf输出而不会弄乱任何东西?

2. 有没有其他方法可以在没有外部库的情况下获取光标位置?我相信 <termios.h> 是可行的,但我找不到有关其工作原理的解释。

解决方法

在我的终端上禁用 ECHO 并禁用规范模式,但将终端设置为 RAW 可能更好。以下代码遗漏了很多错误处理:

#include <stdio.h>
#include <termios.h>
#include <unistd.h>
#include <fcntl.h>    
int main() {
    int x,y;
    int t = STDOUT_FILENO;
    struct termios sav;
    tcgetattr(t,&sav);
    struct termios opt = sav;
    opt.c_lflag &= ~(ECHO | ICANON);
    // but better just cfmakeraw(&opt);
    tcsetattr(t,TCSANOW,&opt);
    printf("\033[6n");
    fflush(stdout);
    scanf("\033[%d;%dR",&x,&y);
    tcsetattr(t,&sav);
    printf("Cursor pos is %d %d\n",x,y);
}