【问题标题】:Prevent output of carriage return with readline使用 readline 防止输出回车
【发布时间】:2015-12-05 12:11:54
【问题描述】:

我是 Gnu Readline 库的新手。

当光标位于控制台的最后一行时,我需要调用readline() 函数。但是当按下 Return 键时,我需要防止向下滚动;所以我正在寻找一种方法来防止输出回车:我确信这是可能的,但找不到方法。

我尝试使用我自己的rl_getc_function() 来捕获 Return 键(下面的示例捕获了 yz 键,但它是仅用于测试目的)并以特殊方式处理此密钥:

  • 我的第一个想法是直接运行accept-line命令,以为它不会输出回车,但实际上,它确实
  • 我的第二个想法是在调用accept-line 命令之前将输出重定向到/dev/null;但是当readline() 函数已经运行时,重定向似乎并不适用。

这是我的测试示例:

#include <stdio.h>
#include <stdlib.h>
#include <readline/readline.h>

FILE *devnull; // To test output redirecting

int my_getc(FILE *file)
{
    int c = getc(file);

    // Let's test something when the 'y' key is pressed:
    if (c == 'y') {
        // I was thinking that calling "accept-line" directly
        // would prevent the output of a carriage return:
        rl_command_func_t *accept_func = rl_named_function("accept-line");
        accept_func(1, 0);
        return 0;
    }

    // Another test, when 'z' key is pressed:
    if (c == 'z') {
        // Try a redirection:
        rl_outstream = devnull;
        // As the redirection didn't work unless I set it before
        // the readline() call, I tried to add this call,
        // but it doesn't initialize the output stream:
        rl_initialize();
        return 'z';

    }
    return c;
}

int main()
{
    devnull = fopen("/dev/null", "w");

    // Using my function to handle key input:
    rl_getc_function = my_getc;

    // Redirection works if I uncomment the following line:
    // rl_outstream = devnull;

    readline("> "); // No freeing for this simplified example
    printf("How is it possible to remove the carriage return before this line?\n");

    return 0;
}

我确定我错过了正确的方法;任何帮助将不胜感激。

【问题讨论】:

    标签: c linux readline


    【解决方案1】:

    我找到了:rl_done 变量就是为此而生的。

    如果我将此代码添加到我的 my_getc() 函数中,它会运行良好:

    if (c == '\r') {
        rl_done = 1;
        return 0;
    
    }
    

    然后不插入回车,我的下一个 printf() 调用显示在我键入的最后一个字符之后。

    【讨论】:

      猜你喜欢
      • 2011-03-31
      • 1970-01-01
      • 2023-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-17
      相关资源
      最近更新 更多