使用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);
}
}
答案 0 :(得分:5)
是的,可以修改readline的编辑缓冲区,例如:使用函数rl_insert_text()
。为了使这个有用,我想你需要使用readline稍微复杂的“回调接口”而不是你的例子中的全唱和跳舞readline()
函数。
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 */
}
}