使用readline防止回车输出

时间:2015-12-05 12:11:54

标签: c linux readline

我是Gnu Readline库的新手。

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

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

  • 我的第一个想法是直接运行accept-line命令,认为它不会输出回车符,但实际上,它确实
  • 我的第二个想法是在调用/dev/null命令之前将输出重定向到accept-line;但是当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;
}

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

1 个答案:

答案 0 :(得分:1)

我找到了它:rl_done变量是为此做的。

如果我将此代码添加到我的my_getc()函数中,则效果很好:

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

}

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

相关问题