我可以使用以下命令将用户输入限制为 5 个字符GNU 阅读线 https://cnswww.cns.cwru.edu/php/chet/readline/rltop.html:
#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
if user types d and Enter return "dummy"
if user types DEL and Enter return "mmy"
在主页上readline
提到了一种可能的用途:
rl.c
是一个示例程序,它使用 Readline 读取用户的一行输入并将其回显到标准输出,适合 shell 脚本使用。
由于编辑现有条目很可能是其中的一部分,因此我决定查看其源代码(直接下载链接 https://cnswww.cns.cwru.edu/php/chet/readline/rl.c)。这确实展示了如何将字符串插入到使用的缓冲区中readline
before它出现在屏幕上,通过使用钩子函数:
变量:rl_hook_func_t *rl_startup_hook
如果非零,则这是之前调用的函数的地址readline
打印第一个提示。
(https://cnswww.cns.cwru.edu/php/chet/readline/readline.html#IDX223 https://cnswww.cns.cwru.edu/php/chet/readline/readline.html#IDX223)
在钩子函数内,您可以直接操作内部缓冲区,例如插入文本:
函数:整数rl_插入_文本 (常量字符*文本)
Insert text进入当前光标位置的行。返回插入的字符数。
(https://cnswww.cns.cwru.edu/php/chet/readline/readline.html#IDX295 https://cnswww.cns.cwru.edu/php/chet/readline/readline.html#IDX295)
钩子函数只需要执行一次(每个函数只调用一次)readline
里面打电话readline_internal_setup
),但显然 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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)