Using GNU Readline:
The function readline()
displays prompt and reads user's input.
Can I modify its internal buffer? and how to achieve that?
#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);
}
}
Yes, one can modify readline's edit buffer, e.g. by using the function rl_insert_text()
. In order to make this useful, I think you'll need to use readline's slightly more complicated "callback interface" instead of the all-singing and dancing readline()
function in your example.
Readline comes with very good and complete documentation, therefore I just give a minimal example program to help you to get started :
/* 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 */
}
}