-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
On Tue, 17 Feb 2004 20:51:53 -1000
"Ryan Walsh"
I'm just getting back into programming, and this is my first introduction to LINUX. I was wondering if anyone had a basic C program on how to read input from the keyboard one character at a time (without having to press enter)... This is not part of standard C, but here is a program that I've had hanging around. The Unix/C FAQ also includes something similar. I've been using this for a while. Essentially, you set the terminal to raw mode, (stdin is file descriptor 0). You should use the basic I/O (eg. read(2) not the stdio routines like getc(3)). #include
#include #include #include #include static struct termio save_term; void SetRaw(int fd) { struct termio s;
/*
* Get terminal modes.
*/
(void)ioctl(fd, TCGETA, &s);
/*
* Save modes and set certain variables dependent on modes.
*/
save_term = s;
/*
* Set the modes to the way we want them.
*/
s.c_lflag &= ~(ICANON|ECHO|ECHOE|ECHOK|ECHONL);
s.c_oflag |= (OPOST|ONLCR|TAB3);
s.c_oflag &= ~(OCRNL|ONOCR|ONLRET);
s.c_cc[VMIN] = 1;
s.c_cc[VTIME] = 0;
(void)ioctl(fd, TCSETAW, &s);
}
static void
TermRestore(int fd)
{
/*
* Restore saved modes.
*/
s = save_term;
(void)ioctl(fd, TCSETAW, &s);
}
int main(int argc, char **argv)
{
int fd, n;
char buf;
fd = 0;
/Set Term to raw mode */
SetRaw(fd);
printf("Enter a digit, q or x to quit\n");
while(1) {
n = read(fd, &buf, 1);
if (n == 1) {
switch(buf) {
case 'q':
case 'Q':
case 'x':
case 'X':
printf("done\n");
TermRestore(fd);
return 0;
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
printf(" %c ", buf);
fflush(stdout);
}
} else if (n == 0) {
printf("no input\n");
TermRestore(fd);
return 0;
} else {
TermRestore(fd);
perror("read\n");
return -1;
}
}
}
- --
Jerry Feldman