Printing while reading characters in C
c, carriage-return, newline, printf, stream
Solution
You actually only need to disable line buffering using termios
Here's an example of doing it:
#include <stdio.h>
#include <stdlib.h>
#include <termios.h>
int main() {
struct termios old_term, new_term;
char c;
/* Get old terminal settings for further restoration */
tcgetattr(0, &old_term);
/* Copy the settings to the new value */
new_term = old_term;
/* Disable echo of the character and line buffering */
new_term.c_lflag &= (~ICANON & ~ECHO);
/* Set new settings to the terminal */
tcsetattr(0, TCSANOW, &new_term);
while ((c = getchar()) != 'q') {
printf("You pressed: %c\n", c);
}
/* Restore old settings */
tcsetattr(0, TCSANOW, &old_term);
return 0;
}
Problem
I'm trying to write a simple little snippet of code to respond to an arrow key press. I know that up is represented by ^[[A, and I have the following code that checks for that sequence: ``` while( 1 ) { input_char = fgetc( stdin ); if( input_char == EOF || input_char == '\n' ) { break; } /* Escape sequence */ if( input_char == 27 ) { input_char = getc( stdin ); if( input_char == '[' ) { switch( getc( stdin ) ) { case 'A': printf("Move up\n"); break; } } } } ``` Whenever I hit "up", the escape sequence (^[[A) shows up on the screen, but "Move up" doesn't appear until I hit enter. The end goal is to replace the text on the current line with some other data, and so I tried to do ``` printf("\r%s", "New Text"); ``` in place of "Move up", but it still doesn't show up until after enter is pressed. Is there something wrong with the way I'm reading in characters? Thanks! EDIT Quick note, it's for *nix systems. SOLUTION Thanks for the pointers everyone. I went with stepanbujnak's solution because it was rather straightforward. The one thing I noticed is that a lot of the behavior of keys that modify the string ( backspace, etc ) is different than you would expect. It will backspace through ANYTHING on the line (including printf'd stuff), and I had to account for that. After that it wasn't too bad getting the rest to fall in line :)