1
0

play_again2.c 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /* play_again2.c
  2. * purpose: ask if user wants another transaction
  3. * method: set tty into char-by-char mode and no-echo mode
  4. * read char, return result
  5. * returns: 0=>yes, 1=>no
  6. * better: timeout if user walks away
  7. *
  8. */
  9. #include <stdio.h>
  10. #include <termios.h>
  11. #define QUESTION "Do you want another transaction"
  12. main()
  13. {
  14. int response;
  15. tty_mode(0); /* save mode */
  16. set_cr_noecho_mode(); /* set -icanon, -echo */
  17. response = get_response(QUESTION); /* get some answer */
  18. tty_mode(1); /* restore tty state */
  19. return response;
  20. }
  21. int get_response(char *question)
  22. /*
  23. * purpose: ask a question and wait for a y/n answer
  24. * method: use getchar and ignore non y/n answers
  25. * returns: 0=>yes, 1=>no
  26. */
  27. {
  28. printf("%s (y/n)?", question);
  29. while(1){
  30. switch( getchar() ){
  31. case 'y':
  32. case 'Y': return 0;
  33. case 'n':
  34. case 'N':
  35. case EOF: return 1;
  36. }
  37. }
  38. }
  39. set_cr_noecho_mode()
  40. /*
  41. * purpose: put file descriptor 0 into chr-by-chr mode and noecho mode
  42. * method: use bits in termios
  43. */
  44. {
  45. struct termios ttystate;
  46. tcgetattr( 0, &ttystate); /* read curr. setting */
  47. ttystate.c_lflag &= ~ICANON; /* no buffering */
  48. ttystate.c_lflag &= ~ECHO; /* no echo either */
  49. ttystate.c_cc[VMIN] = 1; /* get 1 char at a time */
  50. tcsetattr( 0 , TCSANOW, &ttystate); /* install settings */
  51. }
  52. /* how == 0 => save current mode, how == 1 => restore mode */
  53. tty_mode(int how)
  54. {
  55. static struct termios original_mode;
  56. if ( how == 0 )
  57. tcgetattr(0, &original_mode);
  58. else
  59. return tcsetattr(0, TCSANOW, &original_mode);
  60. }