【问题标题】:How to get caret position without external libraries in C/C++ on linux?如何在 Linux 上的 C/C++ 中没有外部库的情况下获得插入符号位置?
【发布时间】:2021-07-13 15:21:15
【问题描述】:

我正在尝试在 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 代码 \033[8m 隐藏 printf("\033[6n"); 的输出,但这只会使字符不可见,这不是我想要的。我想完全摆脱输出。我知道如果我没记错的话,你可以将输出重定向到/dev/null,但我不知道那会不会弄乱光标位置,我还没有尝试过。

所以,两个选项之一:

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

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

【问题讨论】:

  • prints stuff in the terminal 它究竟打印了什么? without external libraries in C/C++ on linux? 为什么没有外部库?为什么不使用ncurses?基本上你想和this bash code做同样的事情,但是在C中。
  • @KamilCuk “在终端中打印内容”我的意思是 printf(\033[6n");" 打印 ^[[45;1R,例如,如果光标位于 x = 45y = 1。并且没有外部库,因为我正在尝试自己做这件事,这不是为了重要的事情,只是为了个人知识

标签: c++ c linux terminal caret


【解决方案1】:

在我的终端上禁用 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, TCSANOW, &sav);
    printf("Cursor pos is %d %d\n", x, y);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-03
    • 1970-01-01
    • 1970-01-01
    • 2011-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多