I need to read the key pressed by the user as they press it without pressing the ENTER key. Current functions that I found in C (getc, fgets, scanf, etc), buffers user input and needs to press ENTER key to read the user input. getch() worked with me, but I want to avoid using the curses library. More research work brought me this code:
#include
#include
#include
#define END_FILE_CHARACTER 0x04 /* ctrl-d is unix-style eof input key*/
int linux_getch(void);
int main()
{
int kb_char;
printf("\n\n This is a test of a function that (more-or-less)\n");
printf(" emulates the classic DOS \"getch()\" function.\n\n");
printf(" The keyboard input is not echoed; each character is\n");
printf(" is returned to the calling program as a key is pressed.\n\n");
printf(" For test purposes, this program echos the hex value returned\n");
printf(" from the keyboard input routine.\n\n");
printf("Press any key(s)");
printf(" (the keyboard routine is set so that ctlr-d is EOF).\n\n");
while ((kb_char = linux_getch()) != EOF) {
printf("%02X ", kb_char);
}
printf("\n\n Function linux_getch() says that you entered EOF\n\n");
return 0;
}
int linux_getch(void)
{
struct termios oldstuff;
struct termios newstuff;
int inch;
tcgetattr(STDIN_FILENO, &oldstuff);
newstuff = oldstuff; /* save old attributes */
newstuff.c_lflag &= ~(ICANON | ECHO); /* reset "canonical" and "echo" flags*/
tcsetattr(STDIN_FILENO, TCSANOW, &newstuff); /* set new attributes */
inch = getchar();
tcsetattr(STDIN_FILENO, TCSANOW, &oldstuff); /* restore old attributes */
if (inch == END_FILE_CHARACTER) {
inch = EOF;
}
return inch;
}
Btw, I also saw how to make this work on Solaris machines. They say that
The termio value of MIN is set to 4 on solaris and set to 1 on linux.
To make it work on both platforms:
After this line:
newstuff.c_lflag &= ~(ICANON | ECHO); /* reset "canonical" and "echo" flags*/
add this line:
newstuff.c_cc[VMIN] = 1;
reference:
http://www.gidforums.com/t-3386.html
No comments:
Post a Comment