What you need to do is check if the character with the getch () function is available. If you use it in non-delay mode, the method will not be blocked. Then you need to eat the characters until you encounter "\ n", adding each char to the resulting string as you go.
Alternatively - and the method I'm using is to use the GNU readline library. It supports non-blocking behavior , but the documentation for this section is not so good.
Here is a small example that you can use. It has a selection loop and uses the GNU readline library:
#include <stdio.h>
#include <readline/readline.h>
#include <readline/history.h>
#include <stdlib.h>
#include <stdbool.h>
int quit = false;
void rl_cb(char* line)
{
if (NULL==line) {
quit = true;
return;
}
if(strlen(line) > 0) add_history(line);
printf("You typed:\n%s\n", line);
free(line);
}
int main()
{
struct timeval to;
const char *prompt = "# ";
rl_callback_handler_install(prompt, (rl_vcpfunc_t*) &rl_cb);
to.tv_sec = 0;
to.tv_usec = 10000;
while(1){
if (quit) break;
select(1, NULL, NULL, NULL, &to);
rl_callback_read_char();
};
rl_callback_handler_remove();
return 0;
}
Compile with:
gcc -Wall rl.c -lreadline
Johan source
share