使用 readline 防止输出回车 return

Prevent output of carriage return with readline

我是 Gnu Readline 库的新手。

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

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

这是我的测试示例:

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

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

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

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

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

}

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