0 Replies - 410 Views - Last Post: 21 May 2010 - 02:42 PM Rate Topic: -----

#1 noclaf   User is offline

  • D.I.C Head
  • member icon

Reputation: 26
  • View blog
  • Posts: 94
  • Joined: 18-April 10

Unbuffered terminal input (Linux)

Posted 21 May 2010 - 02:42 PM

Description: To compile: gcc getch.c -o getchThis emulates the getch() function found in the Windows header <conio.h>. It uses POSIX functionality to achieve single character input without requiring a newline. It should be acceptable as a Linux drop-in replacement to the Windows function.
#include <stdio.h>
#include <termios.h>
#include <unistd.h>

int getch(void) {
  struct termios oldt, newt;
  int ch;

  /* We can't necessarily trust POSIX's STDIN_FILENO */
  int stdin_fd = fileno(stdin);

  /* Get and save the current terminal flags */
  tcgetattr(stdin_fd, &oldt);

  /* Copy the old settings and turn off echo/canonical mode */
  newt = oldt;
  newt.c_lflag &= ~(ICANON | ECHO);

  /* Apply the new settings */
  tcsetattr(stdin_fd, TCSANOW, &newt);

  /* Call the standard getchar() function */
  ch = getchar();

  /* Restore the original settings */
  tcsetattr(stdin_fd, TCSANOW, &oldt);

  return ch;
}

int main(void) {
  int ch;

  /* Output a * for each character typed until a newline is received */
  while ((ch = getch()) != 'n')
    putchar('*');

  return 0;
}



Is This A Good Question/Topic? 0
  • +

Page 1 of 1