使用GNU Readline :
函数readline()
显示提示并读取用户的输入。
我可以修改其内部缓冲区吗?以及如何实现这一目标?
#include <readline/readline.h>
#include <readline/history.h>
int main()
{
char* input;
// Display prompt and read input
input = readline("please enter your name: ");
// Check for EOF.
if (!input)
break;
// Add input to history.
add_history(input);
// Do stuff...
// Free input.
free(input);
}
}
最佳答案
是的,可以修改readline的编辑缓冲区,例如通过使用函数rl_insert_text()
。为了使其有用,我认为您需要使用 readline 稍微复杂的“回调接口(interface)”,而不是你的例子。
Readline 附带了非常好的和完整的 documentation ,因此我只给出一个最小的示例程序来帮助您入门:
/* compile with gcc -o test <this program>.c -lreadline */
#include <stdio.h>
#include <stdlib.h>
#include <readline/readline.h>
void line_handler(char *line) { /* This function (callback) gets called by readline
whenever rl_callback_read_char sees an ENTER */
printf("You changed this into: '%s'\n", line);
exit(0);
}
int main() {
rl_callback_handler_install("Enter a line: ", &line_handler);
rl_insert_text("Heheheh..."); /* insert some text into readline's edit buffer... */
rl_redisplay (); /* Make sure we see it ... */
while (1) {
rl_callback_read_char(); /* read and process one character from stdin */
}
}
关于c - readline() 内部缓冲区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27659931/