Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /****************************************************************
- * getch() implementation *
- * On windows, we have getch() in <conio.h> to get a char from *
- * keyboard without echoing it out to stdout. But Unix has no *
- * <conio.h>, it is not standard though. If we want to use *
- * getch() on Unix, we have to implement it by ourselves. *
- * As <termios.h> is defined in POSIX.1 standard, the code will *
- * be portable and be able to port to ANY Unix-like systems *
- * e.g. Linux, mac, BSD, Solarix, HP-UX, AIX, IRIX, etc. *
- * without any changes in source code. *
- ****************************************************************/
- #include <unistd.h> /* STDIN_FILENO */
- #include <termios.h> /* tcgetattr(3), tcsetattr(3) */
- #include <stdio.h>
- #include <stdlib.h> /* exit(3) */
- int getch(void); /* Prototype */
- int main(void)
- {
- char c; /* Local variable */
- printf("Starting getch(), press space to quit.\n");
- while ((c = (int)getch()) != 0x20) /* Invoke our getch(). */
- printf("You type %c.\n", c);
- /* Once you type a key, it will not be echoed on stdout *
- * directly. It is our choice whether we want to print *
- * it out or not. We prefer to printing the sentence *
- * mentioning what key you have typed. */
- return 0;
- }
- int getch(void) /* Implementation */
- {
- int c; /* Local variable */
- struct termios oldt, newt; /* Declare old and new terminal. */
- /* Get attribute of stdin and store it in "oldt". */
- if (tcgetattr(STDIN_FILENO, &oldt) != 0) {
- fprintf(stderr, "tcgetattr error\n");
- exit(EXIT_FAILURE);
- }
- /* Copy "oldt" to "newt" */
- newt = oldt;
- /* Bitwise-and to turn of canonical mode (ICANON) and echo.*/
- newt.c_lflag &= ~(ICANON | ECHO);
- /* newt.c_cc[VTIME] == 0, so the time is not significant. *
- * Only newt.c_cc[VMIN] is significant. *
- * The read is satisfied when VMIN byte(s), 1 for this case *
- * is received. That is it waits for one byte input, within *
- * indefinite time. Read termios(4) for more information. */
- newt.c_cc[VMIN] = 1;
- newt.c_cc[VTIME] = 0;
- /* Set attribute to "newt", and take effect immediately. */
- if (tcsetattr(STDIN_FILENO, TCSANOW, &newt) != 0) {
- fprintf(stderr, "tcsetattr error\n");
- exit(EXIT_FAILURE);
- }
- /* Since we disabled ECHO and we take input char by char *
- * not canonical (line by line). getchar() will request for *
- * input from a terminal. But now it will not be echoed. */
- c = getchar();
- /* Restore "oldt" prior to ending the function. */
- tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
- return c; /* return a char we have read, but not echod. */
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement