我可以使用
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并输入则返回“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).这确实展示了如何通过使用钩子函数将字符串插入到屏幕上显示的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.
(07001)
在钩子函数内部,您可以直接操作内部缓冲区,例如插入文本:
Function: int rl_insert_text (const char *text)
Insert text into the line at the current cursor position. Returns the number of characters inserted.
(07002)
钩子函数只需要执行一次(在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);