So I have the following code which basically just reads characters user inputs and prints them until 'q' is entered.
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<termios.h>
int main(void) {
char c;
static struct termios oldtio, newtio;
tcgetattr(0, &oldtio);
newtio = oldtio;
newtio.c_lflag &= ~ICANON;
newtio.c_lflag &= ~ECHO;
tcsetattr(0, TCSANOW, &newtio);
printf("Give text: ");
fflush(stdout);
while (1) {
read(0, &c, 1);
printf("%c", c);
fflush(stdout);
if (c == 'q') { break; }
}
printf("\n");
tcsetattr(0, TCSANOW, &oldtio);
return 0;
}
In the beginning of the main function I turn off the canonical mode to make user able to see his input when he's giving it. I also turn off the echo so stuff like "^[[A" doesn't pop up when pressing the up arrow key for example. This works, but I'm also able to move the cursor to upper rows on a terminal window and that's not good. Is there a way fix this so that user can only move within the current row?
Another problem is the backspace. When I press it the program prints a weird symbol (which I assume is 0x7f) instead of erasing the character left to the cursor's current location. I should propably handle the backspace key output in the program somehow but I don't know how to do it since it's this weird hexadecimal number. Any tips for this?
One option I've also been thinking about to make this work is to use canonical mode so the arrow keys and backspace functionalities are automatically in use. However, canonical mode works line by line and so the text doesn't appear until "Enter" is hit by the user. So far, I haven't figured out any way to make user see his input while typing. Is this even possible?
And please, no ncurses or readline suggestions. I want to do this using termios.h.