我可以使用 GNU readline 将用户输入限制为 5 个字符:
#include <readline/readline.h>
#include <stdio.h>
#include <stdlib.h>
static int limit_rl(FILE *f)
{
if (rl_end > 5) {
return '\b';
}
return rl_getc(f);
}
int main(void)
{
char *str;
rl_getc_function = limit_rl;
str = readline("> ");
printf("%s\n", str);
free(str);
return 0;
}
但是,如何读取具有默认值(不是提示)的输入,例如:
> ummy
^ cursor here
如果用户输入 d 和 Enter 返回“dummy”
如果用户键入 DEL 和 Enter 返回“mmy”
最佳答案
在 readline
的主页上提到了一种可能的用法:
rl.c
is an example program that uses Readline to read a line of input from a user and echo it to the standard output, suitable for use by shell scripts.
由于编辑现有条目很可能是其中的一部分,所以我决定查看其来源 (direct download link)。这确实展示了如何通过使用 Hook 函数将字符串插入 readline
在它出现在屏幕上之前使用的缓冲区中:
Variable: rl_hook_func_t * rl_startup_hook
If non-zero, this is the address of a function to call just before
readline
prints the first prompt.
(https://cnswww.cns.cwru.edu/php/chet/readline/readline.html#IDX223)
在钩子(Hook)函数中你可以直接操作内部缓冲区,例如插入文本:
Function: int rl_insert_text (const char *text)
Insert text into the line at the current cursor position. Returns the number of characters inserted.
(https://cnswww.cns.cwru.edu/php/chet/readline/readline.html#IDX295)
hook 函数只需要执行一次(在 readline_internal_setup
中每次 readline
调用只调用一次),但显然 rl 的作者选择了腰带 -吊带接近并在使用后特别禁用它。
来自 rl.c
的相关片段,评论是我的:
/* a global char * to hold a default initial text */
static char *deftext;
/* the callback function. The argument is supposed to be 'void' per
its declaration:
typedef int rl_hook_func_t (void);
so you cannot provide the default text here */
static int set_deftext ()
{
if (deftext)
{
/* Apparently the "current cursor position" in which text is inserted
is 0, when initially called */
rl_insert_text (deftext);
deftext = (char *)NULL;
/* disable the global 'rl_startup_hook' function by setting it to NULL */
rl_startup_hook = (rl_hook_func_t *)NULL;
}
return 0;
}
// ...
if (deftext && *deftext)
rl_startup_hook = set_deftext;
temp = readline (prompt);
关于c - 具有默认值的 readline,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33344163/